Unverified Commit ee7a37f1 authored by Jonah Williams's avatar Jonah Williams Committed by GitHub

[flutter_tools] Ensure that global variables are easily identifiable (#47398)

parent 19c75505
...@@ -25,6 +25,7 @@ final RegExp ignorePattern = RegExp(r'// *ignore:'); ...@@ -25,6 +25,7 @@ final RegExp ignorePattern = RegExp(r'// *ignore:');
final RegExp ignoreForFilePattern = RegExp(r'// *ignore_for_file:'); final RegExp ignoreForFilePattern = RegExp(r'// *ignore_for_file:');
final RegExp asDynamicPattern = RegExp(r'\bas dynamic\b'); final RegExp asDynamicPattern = RegExp(r'\bas dynamic\b');
final RegExp deprecationPattern = RegExp(r'^ *@[dD]eprecated'); final RegExp deprecationPattern = RegExp(r'^ *@[dD]eprecated');
const Pattern globalsPattern = 'globals.';
const String grandfatheredDeprecationPattern = '// ignore: flutter_deprecation_syntax, https'; const String grandfatheredDeprecationPattern = '// ignore: flutter_deprecation_syntax, https';
Future<double> findCostsForFile(File file) async { Future<double> findCostsForFile(File file) async {
...@@ -55,6 +56,17 @@ Future<double> findCostsForFile(File file) async { ...@@ -55,6 +56,17 @@ Future<double> findCostsForFile(File file) async {
return total; return total;
} }
Future<int> findGlobalsForFile(File file) async {
if (path.extension(file.path) != '.dart')
return 0;
int total = 0;
for (String line in await file.readAsLines()) {
if (line.contains(globalsPattern))
total += 1;
}
return total;
}
Future<double> findCostsForRepo() async { Future<double> findCostsForRepo() async {
final Process git = await startProcess( final Process git = await startProcess(
'git', 'git',
...@@ -70,6 +82,21 @@ Future<double> findCostsForRepo() async { ...@@ -70,6 +82,21 @@ Future<double> findCostsForRepo() async {
return total; return total;
} }
Future<int> findGlobalsForTool() async {
final Process git = await startProcess(
'git',
<String>['ls-files', '--full-name', path.join(flutterDirectory.path, 'packages', 'flutter_tools')],
workingDirectory: flutterDirectory.path,
);
int total = 0;
await for (String entry in git.stdout.transform<String>(utf8.decoder).transform<String>(const LineSplitter()))
total += await findGlobalsForFile(File(path.join(flutterDirectory.path, entry)));
final int gitExitCode = await git.exitCode;
if (gitExitCode != 0)
throw Exception('git exit with unexpected error code $gitExitCode');
return total;
}
Future<int> countDependencies() async { Future<int> countDependencies() async {
final List<String> lines = (await evalFlutter( final List<String> lines = (await evalFlutter(
'update-packages', 'update-packages',
...@@ -95,6 +122,7 @@ Future<int> countConsumerDependencies() async { ...@@ -95,6 +122,7 @@ Future<int> countConsumerDependencies() async {
const String _kCostBenchmarkKey = 'technical_debt_in_dollars'; const String _kCostBenchmarkKey = 'technical_debt_in_dollars';
const String _kNumberOfDependenciesKey = 'dependencies_count'; const String _kNumberOfDependenciesKey = 'dependencies_count';
const String _kNumberOfConsumerDependenciesKey = 'consumer_dependencies_count'; const String _kNumberOfConsumerDependenciesKey = 'consumer_dependencies_count';
const String _kNumberOfFlutterToolGlobals = 'flutter_tool_globals_count';
Future<void> main() async { Future<void> main() async {
await task(() async { await task(() async {
...@@ -103,6 +131,7 @@ Future<void> main() async { ...@@ -103,6 +131,7 @@ Future<void> main() async {
_kCostBenchmarkKey: await findCostsForRepo(), _kCostBenchmarkKey: await findCostsForRepo(),
_kNumberOfDependenciesKey: await countDependencies(), _kNumberOfDependenciesKey: await countDependencies(),
_kNumberOfConsumerDependenciesKey: await countConsumerDependencies(), _kNumberOfConsumerDependenciesKey: await countConsumerDependencies(),
_kNumberOfFlutterToolGlobals: await findGlobalsForTool(),
}, },
benchmarkScoreKeys: <String>[ benchmarkScoreKeys: <String>[
_kCostBenchmarkKey, _kCostBenchmarkKey,
......
...@@ -95,9 +95,7 @@ dart_tool("fuchsia_asset_builder") { ...@@ -95,9 +95,7 @@ dart_tool("fuchsia_asset_builder") {
"src/base/logger.dart", "src/base/logger.dart",
"src/base/net.dart", "src/base/net.dart",
"src/base/os.dart", "src/base/os.dart",
"src/base/platform.dart",
"src/base/process.dart", "src/base/process.dart",
"src/base/process_manager.dart",
"src/base/terminal.dart", "src/base/terminal.dart",
"src/base/utils.dart", "src/base/utils.dart",
"src/base/version.dart", "src/base/version.dart",
...@@ -183,9 +181,7 @@ dart_tool("fuchsia_tester") { ...@@ -183,9 +181,7 @@ dart_tool("fuchsia_tester") {
"src/base/logger.dart", "src/base/logger.dart",
"src/base/net.dart", "src/base/net.dart",
"src/base/os.dart", "src/base/os.dart",
"src/base/platform.dart",
"src/base/process.dart", "src/base/process.dart",
"src/base/process_manager.dart",
"src/base/terminal.dart", "src/base/terminal.dart",
"src/base/utils.dart", "src/base/utils.dart",
"src/base/version.dart", "src/base/version.dart",
......
...@@ -9,12 +9,11 @@ import 'package:flutter_tools/src/asset.dart' hide defaultManifestPath; ...@@ -9,12 +9,11 @@ import 'package:flutter_tools/src/asset.dart' hide defaultManifestPath;
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' as libfs; import 'package:flutter_tools/src/base/file_system.dart' as libfs;
import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/cache.dart'; import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/context_runner.dart'; import 'package:flutter_tools/src/context_runner.dart';
import 'package:flutter_tools/src/devfs.dart'; import 'package:flutter_tools/src/devfs.dart';
import 'package:flutter_tools/src/bundle.dart'; import 'package:flutter_tools/src/bundle.dart';
import 'package:flutter_tools/src/globals.dart'; import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:flutter_tools/src/reporting/reporting.dart';
const String _kOptionPackages = 'packages'; const String _kOptionPackages = 'packages';
...@@ -52,10 +51,10 @@ Future<void> run(List<String> args) async { ...@@ -52,10 +51,10 @@ Future<void> run(List<String> args) async {
final ArgResults argResults = parser.parse(args); final ArgResults argResults = parser.parse(args);
if (_kRequiredOptions if (_kRequiredOptions
.any((String option) => !argResults.options.contains(option))) { .any((String option) => !argResults.options.contains(option))) {
printError('Missing option! All options must be specified.'); globals.printError('Missing option! All options must be specified.');
exit(1); exit(1);
} }
Cache.flutterRoot = platform.environment['FLUTTER_ROOT']; Cache.flutterRoot = globals.platform.environment['FLUTTER_ROOT'];
final String assetDir = argResults[_kOptionAsset] as String; final String assetDir = argResults[_kOptionAsset] as String;
final AssetBundle assets = await buildAssets( final AssetBundle assets = await buildAssets(
...@@ -72,7 +71,7 @@ Future<void> run(List<String> args) async { ...@@ -72,7 +71,7 @@ Future<void> run(List<String> args) async {
final List<Future<void>> calls = <Future<void>>[]; final List<Future<void>> calls = <Future<void>>[];
assets.entries.forEach((String fileName, DevFSContent content) { assets.entries.forEach((String fileName, DevFSContent content) {
final libfs.File outputFile = libfs.fs.file(libfs.fs.path.join(assetDir, fileName)); final libfs.File outputFile = globals.fs.file(globals.fs.path.join(assetDir, fileName));
calls.add(writeFile(outputFile, content)); calls.add(writeFile(outputFile, content));
}); });
await Future.wait<void>(calls); await Future.wait<void>(calls);
...@@ -83,7 +82,7 @@ Future<void> run(List<String> args) async { ...@@ -83,7 +82,7 @@ Future<void> run(List<String> args) async {
Future<void> writeFuchsiaManifest(AssetBundle assets, String outputBase, String fileDest, String componentName) async { Future<void> writeFuchsiaManifest(AssetBundle assets, String outputBase, String fileDest, String componentName) async {
final libfs.File destFile = libfs.fs.file(fileDest); final libfs.File destFile = globals.fs.file(fileDest);
await destFile.create(recursive: true); await destFile.create(recursive: true);
final libfs.IOSink outFile = destFile.openWrite(); final libfs.IOSink outFile = destFile.openWrite();
......
...@@ -17,6 +17,7 @@ import 'package:flutter_tools/src/commands/doctor.dart'; ...@@ -17,6 +17,7 @@ import 'package:flutter_tools/src/commands/doctor.dart';
import 'package:flutter_tools/src/device.dart'; import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/fuchsia/fuchsia_device.dart'; import 'package:flutter_tools/src/fuchsia/fuchsia_device.dart';
import 'package:flutter_tools/src/fuchsia/fuchsia_sdk.dart'; import 'package:flutter_tools/src/fuchsia/fuchsia_sdk.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart'; import 'package:flutter_tools/src/runner/flutter_command.dart';
...@@ -40,20 +41,20 @@ Future<void> main(List<String> args) async { ...@@ -40,20 +41,20 @@ Future<void> main(List<String> args) async {
final List<String> targetParts = _extractPathAndName(target); final List<String> targetParts = _extractPathAndName(target);
final String path = targetParts[0]; final String path = targetParts[0];
final String name = targetParts[1]; final String name = targetParts[1];
final File dartSdk = fs.file(argResults['dart-sdk']); final File dartSdk = globals.fs.file(argResults['dart-sdk']);
final String buildDirectory = argResults['build-dir'] as String; final String buildDirectory = argResults['build-dir'] as String;
final File frontendServer = fs.file('$buildDirectory/host_x64/gen/third_party/flutter/frontend_server/frontend_server_tool.snapshot'); final File frontendServer = globals.fs.file('$buildDirectory/host_x64/gen/third_party/flutter/frontend_server/frontend_server_tool.snapshot');
final File sshConfig = fs.file('$buildDirectory/ssh-keys/ssh_config'); final File sshConfig = globals.fs.file('$buildDirectory/ssh-keys/ssh_config');
final File devFinder = fs.file(argResults['dev-finder']); final File devFinder = globals.fs.file(argResults['dev-finder']);
final File platformKernelDill = fs.file('$buildDirectory/flutter_runner_patched_sdk/platform_strong.dill'); final File platformKernelDill = globals.fs.file('$buildDirectory/flutter_runner_patched_sdk/platform_strong.dill');
final File flutterPatchedSdk = fs.file('$buildDirectory/flutter_runner_patched_sdk'); final File flutterPatchedSdk = globals.fs.file('$buildDirectory/flutter_runner_patched_sdk');
final String packages = '$buildDirectory/dartlang/gen/$path/${name}_dart_library.packages'; final String packages = '$buildDirectory/dartlang/gen/$path/${name}_dart_library.packages';
final String outputDill = '$buildDirectory/${name}_tmp.dill'; final String outputDill = '$buildDirectory/${name}_tmp.dill';
// TODO(jonahwilliams): running from fuchsia root hangs hot reload for some reason. // TODO(jonahwilliams): running from fuchsia root hangs hot reload for some reason.
// switch to the project root directory and run from there. // switch to the project root directory and run from there.
originalWorkingDirectory = fs.currentDirectory.path; originalWorkingDirectory = globals.fs.currentDirectory.path;
fs.currentDirectory = path; globals.fs.currentDirectory = path;
if (!devFinder.existsSync()) { if (!devFinder.existsSync()) {
print('Error: dev_finder not found at ${devFinder.path}.'); print('Error: dev_finder not found at ${devFinder.path}.');
...@@ -71,7 +72,7 @@ Future<void> main(List<String> args) async { ...@@ -71,7 +72,7 @@ Future<void> main(List<String> args) async {
// Check for a package with a lib directory. // Check for a package with a lib directory.
final String entrypoint = argResults['entrypoint'] as String; final String entrypoint = argResults['entrypoint'] as String;
String targetFile = 'lib/$entrypoint'; String targetFile = 'lib/$entrypoint';
if (!fs.file(targetFile).existsSync()) { if (!globals.fs.file(targetFile).existsSync()) {
// Otherwise assume the package is flat. // Otherwise assume the package is flat.
targetFile = entrypoint; targetFile = entrypoint;
} }
......
...@@ -11,13 +11,13 @@ import 'package:flutter_tools/src/base/common.dart'; ...@@ -11,13 +11,13 @@ import 'package:flutter_tools/src/base/common.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/file_system.dart';
import 'package:flutter_tools/src/base/io.dart'; import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/platform.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/context_runner.dart'; import 'package:flutter_tools/src/context_runner.dart';
import 'package:flutter_tools/src/dart/package_map.dart'; import 'package:flutter_tools/src/dart/package_map.dart';
import 'package:flutter_tools/src/artifacts.dart'; import 'package:flutter_tools/src/artifacts.dart';
import 'package:flutter_tools/src/globals.dart'; import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/project.dart'; import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/reporting/reporting.dart'; import 'package:flutter_tools/src/reporting/reporting.dart';
import 'package:flutter_tools/src/test/coverage_collector.dart'; import 'package:flutter_tools/src/test/coverage_collector.dart';
...@@ -73,46 +73,46 @@ Future<void> run(List<String> args) async { ...@@ -73,46 +73,46 @@ Future<void> run(List<String> args) async {
throwToolExit('Missing option! All options must be specified.'); throwToolExit('Missing option! All options must be specified.');
} }
final Directory tempDir = final Directory tempDir =
fs.systemTempDirectory.createTempSync('flutter_fuchsia_tester.'); globals.fs.systemTempDirectory.createTempSync('flutter_fuchsia_tester.');
try { try {
Cache.flutterRoot = tempDir.path; Cache.flutterRoot = tempDir.path;
final String shellPath = fs.file(argResults[_kOptionShell]).resolveSymbolicLinksSync(); final String shellPath = globals.fs.file(argResults[_kOptionShell]).resolveSymbolicLinksSync();
if (!fs.isFileSync(shellPath)) { if (!globals.fs.isFileSync(shellPath)) {
throwToolExit('Cannot find Flutter shell at $shellPath'); throwToolExit('Cannot find Flutter shell at $shellPath');
} }
final Directory sdkRootSrc = fs.directory(argResults[_kOptionSdkRoot]); final Directory sdkRootSrc = globals.fs.directory(argResults[_kOptionSdkRoot]);
if (!fs.isDirectorySync(sdkRootSrc.path)) { if (!globals.fs.isDirectorySync(sdkRootSrc.path)) {
throwToolExit('Cannot find SDK files at ${sdkRootSrc.path}'); throwToolExit('Cannot find SDK files at ${sdkRootSrc.path}');
} }
Directory coverageDirectory; Directory coverageDirectory;
final String coverageDirectoryPath = argResults[_kOptionCoverageDirectory] as String; final String coverageDirectoryPath = argResults[_kOptionCoverageDirectory] as String;
if (coverageDirectoryPath != null) { if (coverageDirectoryPath != null) {
if (!fs.isDirectorySync(coverageDirectoryPath)) { if (!globals.fs.isDirectorySync(coverageDirectoryPath)) {
throwToolExit('Cannot find coverage directory at $coverageDirectoryPath'); throwToolExit('Cannot find coverage directory at $coverageDirectoryPath');
} }
coverageDirectory = fs.directory(coverageDirectoryPath); coverageDirectory = globals.fs.directory(coverageDirectoryPath);
} }
// Put the tester shell where runTests expects it. // Put the tester shell where runTests expects it.
// TODO(garymm): Switch to a Fuchsia-specific Artifacts impl. // TODO(garymm): Switch to a Fuchsia-specific Artifacts impl.
final Link testerDestLink = final Link testerDestLink =
fs.link(artifacts.getArtifactPath(Artifact.flutterTester)); globals.fs.link(globals.artifacts.getArtifactPath(Artifact.flutterTester));
testerDestLink.parent.createSync(recursive: true); testerDestLink.parent.createSync(recursive: true);
testerDestLink.createSync(fs.path.absolute(shellPath)); testerDestLink.createSync(globals.fs.path.absolute(shellPath));
final Directory sdkRootDest = final Directory sdkRootDest =
fs.directory(artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath)); globals.fs.directory(globals.artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath));
sdkRootDest.createSync(recursive: true); sdkRootDest.createSync(recursive: true);
for (FileSystemEntity artifact in sdkRootSrc.listSync()) { for (FileSystemEntity artifact in sdkRootSrc.listSync()) {
fs.link(sdkRootDest.childFile(artifact.basename).path).createSync(artifact.path); globals.fs.link(sdkRootDest.childFile(artifact.basename).path).createSync(artifact.path);
} }
// TODO(tvolkert): Remove once flutter_tester no longer looks for this. // TODO(tvolkert): Remove once flutter_tester no longer looks for this.
fs.link(sdkRootDest.childFile('platform.dill').path).createSync('platform_strong.dill'); globals.fs.link(sdkRootDest.childFile('platform.dill').path).createSync('platform_strong.dill');
PackageMap.globalPackagesPath = PackageMap.globalPackagesPath =
fs.path.normalize(fs.path.absolute(argResults[_kOptionPackages] as String)); globals.fs.path.normalize(globals.fs.path.absolute(argResults[_kOptionPackages] as String));
Directory testDirectory; Directory testDirectory;
CoverageCollector collector; CoverageCollector collector;
...@@ -129,16 +129,16 @@ Future<void> run(List<String> args) async { ...@@ -129,16 +129,16 @@ Future<void> run(List<String> args) async {
if (!argResults.options.contains(_kOptionTestDirectory)) { if (!argResults.options.contains(_kOptionTestDirectory)) {
throwToolExit('Use of --coverage requires setting --test-directory'); throwToolExit('Use of --coverage requires setting --test-directory');
} }
testDirectory = fs.directory(argResults[_kOptionTestDirectory]); testDirectory = globals.fs.directory(argResults[_kOptionTestDirectory]);
} }
final Map<String, String> tests = <String, String>{}; final Map<String, String> tests = <String, String>{};
final List<Map<String, dynamic>> jsonList = List<Map<String, dynamic>>.from( final List<Map<String, dynamic>> jsonList = List<Map<String, dynamic>>.from(
(json.decode(fs.file(argResults[_kOptionTests]).readAsStringSync()) as List<dynamic>).cast<Map<String, dynamic>>()); (json.decode(globals.fs.file(argResults[_kOptionTests]).readAsStringSync()) as List<dynamic>).cast<Map<String, dynamic>>());
for (Map<String, dynamic> map in jsonList) { for (Map<String, dynamic> map in jsonList) {
final String source = fs.file(map['source']).resolveSymbolicLinksSync(); final String source = globals.fs.file(map['source']).resolveSymbolicLinksSync();
final String dill = fs.file(map['dill']).resolveSymbolicLinksSync(); final String dill = globals.fs.file(map['dill']).resolveSymbolicLinksSync();
tests[source] = dill; tests[source] = dill;
} }
...@@ -151,8 +151,8 @@ Future<void> run(List<String> args) async { ...@@ -151,8 +151,8 @@ Future<void> run(List<String> args) async {
enableObservatory: collector != null, enableObservatory: collector != null,
buildMode: BuildMode.debug, buildMode: BuildMode.debug,
precompiledDillFiles: tests, precompiledDillFiles: tests,
concurrency: math.max(1, platform.numberOfProcessors - 2), concurrency: math.max(1, globals.platform.numberOfProcessors - 2),
icudtlPath: fs.path.absolute(argResults[_kOptionIcudtl] as String), icudtlPath: globals.fs.path.absolute(argResults[_kOptionIcudtl] as String),
coverageDirectory: coverageDirectory, coverageDirectory: coverageDirectory,
); );
...@@ -161,9 +161,9 @@ Future<void> run(List<String> args) async { ...@@ -161,9 +161,9 @@ Future<void> run(List<String> args) async {
// package (i.e. contains lib/ and test/ sub-dirs). In some cases, // package (i.e. contains lib/ and test/ sub-dirs). In some cases,
// test files may appear to be in the root directory. // test files may appear to be in the root directory.
if (coverageDirectory == null) { if (coverageDirectory == null) {
fs.currentDirectory = testDirectory.parent; globals.fs.currentDirectory = testDirectory.parent;
} else { } else {
fs.currentDirectory = testDirectory; globals.fs.currentDirectory = testDirectory;
} }
if (!await collector.collectCoverageData(argResults[_kOptionCoveragePath] as String, coverageDirectory: coverageDirectory)) { if (!await collector.collectCoverageData(argResults[_kOptionCoveragePath] as String, coverageDirectory: coverageDirectory)) {
throwToolExit('Failed to collect coverage data'); throwToolExit('Failed to collect coverage data');
......
...@@ -10,6 +10,7 @@ import '../android/gradle_errors.dart'; ...@@ -10,6 +10,7 @@ import '../android/gradle_errors.dart';
import '../base/context.dart'; import '../base/context.dart';
import '../base/file_system.dart'; import '../base/file_system.dart';
import '../build_info.dart'; import '../build_info.dart';
import '../globals.dart' as globals;
import '../project.dart'; import '../project.dart';
import 'android_sdk.dart'; import 'android_sdk.dart';
import 'gradle.dart'; import 'gradle.dart';
...@@ -62,7 +63,7 @@ class _AndroidBuilderImpl extends AndroidBuilder { ...@@ -62,7 +63,7 @@ class _AndroidBuilderImpl extends AndroidBuilder {
}) async { }) async {
try { try {
Directory outputDirectory = Directory outputDirectory =
fs.directory(outputDirectoryPath ?? project.android.buildDirectory); globals.fs.directory(outputDirectoryPath ?? project.android.buildDirectory);
if (project.isModule) { if (project.isModule) {
// Module projects artifacts are located in `build/host`. // Module projects artifacts are located in `build/host`.
outputDirectory = outputDirectory.childDirectory('host'); outputDirectory = outputDirectory.childDirectory('host');
......
...@@ -12,6 +12,7 @@ import '../base/file_system.dart'; ...@@ -12,6 +12,7 @@ import '../base/file_system.dart';
import '../base/process.dart'; import '../base/process.dart';
import '../device.dart'; import '../device.dart';
import '../emulator.dart'; import '../emulator.dart';
import '../globals.dart' as globals;
import 'android_sdk.dart'; import 'android_sdk.dart';
class AndroidEmulators extends EmulatorDiscovery { class AndroidEmulators extends EmulatorDiscovery {
...@@ -93,12 +94,12 @@ AndroidEmulator _loadEmulatorInfo(String id) { ...@@ -93,12 +94,12 @@ AndroidEmulator _loadEmulatorInfo(String id) {
id = id.trim(); id = id.trim();
final String avdPath = getAvdPath(); final String avdPath = getAvdPath();
if (avdPath != null) { if (avdPath != null) {
final File iniFile = fs.file(fs.path.join(avdPath, '$id.ini')); final File iniFile = globals.fs.file(globals.fs.path.join(avdPath, '$id.ini'));
if (iniFile.existsSync()) { if (iniFile.existsSync()) {
final Map<String, String> ini = parseIniLines(iniFile.readAsLinesSync()); final Map<String, String> ini = parseIniLines(iniFile.readAsLinesSync());
if (ini['path'] != null) { if (ini['path'] != null) {
final File configFile = final File configFile =
fs.file(fs.path.join(ini['path'], 'config.ini')); globals.fs.file(globals.fs.path.join(ini['path'], 'config.ini'));
if (configFile.existsSync()) { if (configFile.existsSync()) {
final Map<String, String> properties = final Map<String, String> properties =
parseIniLines(configFile.readAsLinesSync()); parseIniLines(configFile.readAsLinesSync());
......
...@@ -5,12 +5,10 @@ ...@@ -5,12 +5,10 @@
import '../base/common.dart'; import '../base/common.dart';
import '../base/context.dart'; import '../base/context.dart';
import '../base/file_system.dart'; import '../base/file_system.dart';
import '../base/platform.dart';
import '../base/process.dart'; import '../base/process.dart';
import '../base/process_manager.dart';
import '../base/utils.dart'; import '../base/utils.dart';
import '../base/version.dart'; import '../base/version.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import '../ios/plist_parser.dart'; import '../ios/plist_parser.dart';
AndroidStudio get androidStudio => context.get<AndroidStudio>(); AndroidStudio get androidStudio => context.get<AndroidStudio>();
...@@ -41,15 +39,15 @@ class AndroidStudio implements Comparable<AndroidStudio> { ...@@ -41,15 +39,15 @@ class AndroidStudio implements Comparable<AndroidStudio> {
} }
factory AndroidStudio.fromMacOSBundle(String bundlePath) { factory AndroidStudio.fromMacOSBundle(String bundlePath) {
String studioPath = fs.path.join(bundlePath, 'Contents'); String studioPath = globals.fs.path.join(bundlePath, 'Contents');
String plistFile = fs.path.join(studioPath, 'Info.plist'); String plistFile = globals.fs.path.join(studioPath, 'Info.plist');
Map<String, dynamic> plistValues = PlistParser.instance.parseFile(plistFile); Map<String, dynamic> plistValues = PlistParser.instance.parseFile(plistFile);
// As AndroidStudio managed by JetBrainsToolbox could have a wrapper pointing to the real Android Studio. // As AndroidStudio managed by JetBrainsToolbox could have a wrapper pointing to the real Android Studio.
// Check if we've found a JetBrainsToolbox wrapper and deal with it properly. // Check if we've found a JetBrainsToolbox wrapper and deal with it properly.
final String jetBrainsToolboxAppBundlePath = plistValues['JetBrainsToolboxApp'] as String; final String jetBrainsToolboxAppBundlePath = plistValues['JetBrainsToolboxApp'] as String;
if (jetBrainsToolboxAppBundlePath != null) { if (jetBrainsToolboxAppBundlePath != null) {
studioPath = fs.path.join(jetBrainsToolboxAppBundlePath, 'Contents'); studioPath = globals.fs.path.join(jetBrainsToolboxAppBundlePath, 'Contents');
plistFile = fs.path.join(studioPath, 'Info.plist'); plistFile = globals.fs.path.join(studioPath, 'Info.plist');
plistValues = PlistParser.instance.parseFile(plistFile); plistValues = PlistParser.instance.parseFile(plistFile);
} }
...@@ -70,7 +68,7 @@ class AndroidStudio implements Comparable<AndroidStudio> { ...@@ -70,7 +68,7 @@ class AndroidStudio implements Comparable<AndroidStudio> {
} }
final String presetPluginsPath = pathsSelectorValue == null final String presetPluginsPath = pathsSelectorValue == null
? null ? null
: fs.path.join(homeDirPath, 'Library', 'Application Support', '$pathsSelectorValue'); : globals.fs.path.join(homeDirPath, 'Library', 'Application Support', '$pathsSelectorValue');
return AndroidStudio(studioPath, version: version, presetPluginsPath: presetPluginsPath); return AndroidStudio(studioPath, version: version, presetPluginsPath: presetPluginsPath);
} }
...@@ -87,13 +85,13 @@ class AndroidStudio implements Comparable<AndroidStudio> { ...@@ -87,13 +85,13 @@ class AndroidStudio implements Comparable<AndroidStudio> {
} }
String installPath; String installPath;
try { try {
installPath = fs installPath = globals.fs
.file(fs.path.join(homeDotDir.path, 'system', '.home')) .file(globals.fs.path.join(homeDotDir.path, 'system', '.home'))
.readAsStringSync(); .readAsStringSync();
} catch (e) { } catch (e) {
// ignored, installPath will be null, which is handled below // ignored, installPath will be null, which is handled below
} }
if (installPath != null && fs.isDirectorySync(installPath)) { if (installPath != null && globals.fs.isDirectorySync(installPath)) {
return AndroidStudio( return AndroidStudio(
installPath, installPath,
version: version, version: version,
...@@ -123,14 +121,14 @@ class AndroidStudio implements Comparable<AndroidStudio> { ...@@ -123,14 +121,14 @@ class AndroidStudio implements Comparable<AndroidStudio> {
} }
final int major = version?.major; final int major = version?.major;
final int minor = version?.minor; final int minor = version?.minor;
if (platform.isMacOS) { if (globals.platform.isMacOS) {
return fs.path.join( return globals.fs.path.join(
homeDirPath, homeDirPath,
'Library', 'Library',
'Application Support', 'Application Support',
'AndroidStudio$major.$minor'); 'AndroidStudio$major.$minor');
} else { } else {
return fs.path.join(homeDirPath, return globals.fs.path.join(homeDirPath,
'.$studioAppName$major.$minor', '.$studioAppName$major.$minor',
'config', 'config',
'plugins'); 'plugins');
...@@ -150,11 +148,11 @@ class AndroidStudio implements Comparable<AndroidStudio> { ...@@ -150,11 +148,11 @@ class AndroidStudio implements Comparable<AndroidStudio> {
/// Locates the newest, valid version of Android Studio. /// Locates the newest, valid version of Android Studio.
static AndroidStudio latestValid() { static AndroidStudio latestValid() {
final String configuredStudio = config.getValue('android-studio-dir') as String; final String configuredStudio = globals.config.getValue('android-studio-dir') as String;
if (configuredStudio != null) { if (configuredStudio != null) {
String configuredStudioPath = configuredStudio; String configuredStudioPath = configuredStudio;
if (platform.isMacOS && !configuredStudioPath.endsWith('Contents')) { if (globals.platform.isMacOS && !configuredStudioPath.endsWith('Contents')) {
configuredStudioPath = fs.path.join(configuredStudioPath, 'Contents'); configuredStudioPath = globals.fs.path.join(configuredStudioPath, 'Contents');
} }
return AndroidStudio(configuredStudioPath, return AndroidStudio(configuredStudioPath,
configured: configuredStudio); configured: configuredStudio);
...@@ -171,17 +169,17 @@ class AndroidStudio implements Comparable<AndroidStudio> { ...@@ -171,17 +169,17 @@ class AndroidStudio implements Comparable<AndroidStudio> {
} }
static List<AndroidStudio> allInstalled() => static List<AndroidStudio> allInstalled() =>
platform.isMacOS ? _allMacOS() : _allLinuxOrWindows(); globals.platform.isMacOS ? _allMacOS() : _allLinuxOrWindows();
static List<AndroidStudio> _allMacOS() { static List<AndroidStudio> _allMacOS() {
final List<FileSystemEntity> candidatePaths = <FileSystemEntity>[]; final List<FileSystemEntity> candidatePaths = <FileSystemEntity>[];
void _checkForStudio(String path) { void _checkForStudio(String path) {
if (!fs.isDirectorySync(path)) { if (!globals.fs.isDirectorySync(path)) {
return; return;
} }
try { try {
final Iterable<Directory> directories = fs final Iterable<Directory> directories = globals.fs
.directory(path) .directory(path)
.listSync(followLinks: false) .listSync(followLinks: false)
.whereType<Directory>(); .whereType<Directory>();
...@@ -195,16 +193,16 @@ class AndroidStudio implements Comparable<AndroidStudio> { ...@@ -195,16 +193,16 @@ class AndroidStudio implements Comparable<AndroidStudio> {
} }
} }
} catch (e) { } catch (e) {
printTrace('Exception while looking for Android Studio: $e'); globals.printTrace('Exception while looking for Android Studio: $e');
} }
} }
_checkForStudio('/Applications'); _checkForStudio('/Applications');
_checkForStudio(fs.path.join(homeDirPath, 'Applications')); _checkForStudio(globals.fs.path.join(homeDirPath, 'Applications'));
final String configuredStudioDir = config.getValue('android-studio-dir') as String; final String configuredStudioDir = globals.config.getValue('android-studio-dir') as String;
if (configuredStudioDir != null) { if (configuredStudioDir != null) {
FileSystemEntity configuredStudio = fs.file(configuredStudioDir); FileSystemEntity configuredStudio = globals.fs.file(configuredStudioDir);
if (configuredStudio.basename == 'Contents') { if (configuredStudio.basename == 'Contents') {
configuredStudio = configuredStudio.parent; configuredStudio = configuredStudio.parent;
} }
...@@ -237,8 +235,8 @@ class AndroidStudio implements Comparable<AndroidStudio> { ...@@ -237,8 +235,8 @@ class AndroidStudio implements Comparable<AndroidStudio> {
// Read all $HOME/.AndroidStudio*/system/.home files. There may be several // Read all $HOME/.AndroidStudio*/system/.home files. There may be several
// pointing to the same installation, so we grab only the latest one. // pointing to the same installation, so we grab only the latest one.
if (homeDirPath != null && fs.directory(homeDirPath).existsSync()) { if (homeDirPath != null && globals.fs.directory(homeDirPath).existsSync()) {
for (FileSystemEntity entity in fs.directory(homeDirPath).listSync(followLinks: false)) { for (FileSystemEntity entity in globals.fs.directory(homeDirPath).listSync(followLinks: false)) {
if (entity is Directory && entity.basename.startsWith('.AndroidStudio')) { if (entity is Directory && entity.basename.startsWith('.AndroidStudio')) {
final AndroidStudio studio = AndroidStudio.fromHomeDot(entity); final AndroidStudio studio = AndroidStudio.fromHomeDot(entity);
if (studio != null && !_hasStudioAt(studio.directory, newerThan: studio.version)) { if (studio != null && !_hasStudioAt(studio.directory, newerThan: studio.version)) {
...@@ -249,15 +247,15 @@ class AndroidStudio implements Comparable<AndroidStudio> { ...@@ -249,15 +247,15 @@ class AndroidStudio implements Comparable<AndroidStudio> {
} }
} }
final String configuredStudioDir = config.getValue('android-studio-dir') as String; final String configuredStudioDir = globals.config.getValue('android-studio-dir') as String;
if (configuredStudioDir != null && !_hasStudioAt(configuredStudioDir)) { if (configuredStudioDir != null && !_hasStudioAt(configuredStudioDir)) {
studios.add(AndroidStudio(configuredStudioDir, studios.add(AndroidStudio(configuredStudioDir,
configured: configuredStudioDir)); configured: configuredStudioDir));
} }
if (platform.isLinux) { if (globals.platform.isLinux) {
void _checkWellKnownPath(String path) { void _checkWellKnownPath(String path) {
if (fs.isDirectorySync(path) && !_hasStudioAt(path)) { if (globals.fs.isDirectorySync(path) && !_hasStudioAt(path)) {
studios.add(AndroidStudio(path)); studios.add(AndroidStudio(path));
} }
} }
...@@ -284,16 +282,16 @@ class AndroidStudio implements Comparable<AndroidStudio> { ...@@ -284,16 +282,16 @@ class AndroidStudio implements Comparable<AndroidStudio> {
_validationMessages.add('android-studio-dir = $configured'); _validationMessages.add('android-studio-dir = $configured');
} }
if (!fs.isDirectorySync(directory)) { if (!globals.fs.isDirectorySync(directory)) {
_validationMessages.add('Android Studio not found at $directory'); _validationMessages.add('Android Studio not found at $directory');
return; return;
} }
final String javaPath = platform.isMacOS ? final String javaPath = globals.platform.isMacOS ?
fs.path.join(directory, 'jre', 'jdk', 'Contents', 'Home') : globals.fs.path.join(directory, 'jre', 'jdk', 'Contents', 'Home') :
fs.path.join(directory, 'jre'); globals.fs.path.join(directory, 'jre');
final String javaExecutable = fs.path.join(javaPath, 'bin', 'java'); final String javaExecutable = globals.fs.path.join(javaPath, 'bin', 'java');
if (!processManager.canRun(javaExecutable)) { if (!globals.processManager.canRun(javaExecutable)) {
_validationMessages.add('Unable to find bundled Java version.'); _validationMessages.add('Unable to find bundled Java version.');
} else { } else {
final RunResult result = processUtils.runSync(<String>[javaExecutable, '-version']); final RunResult result = processUtils.runSync(<String>[javaExecutable, '-version']);
......
...@@ -7,7 +7,7 @@ import 'dart:async'; ...@@ -7,7 +7,7 @@ import 'dart:async';
import '../base/user_messages.dart'; import '../base/user_messages.dart';
import '../base/version.dart'; import '../base/version.dart';
import '../doctor.dart'; import '../doctor.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import '../intellij/intellij.dart'; import '../intellij/intellij.dart';
import 'android_studio.dart'; import 'android_studio.dart';
...@@ -71,7 +71,7 @@ class NoAndroidStudioValidator extends DoctorValidator { ...@@ -71,7 +71,7 @@ class NoAndroidStudioValidator extends DoctorValidator {
Future<ValidationResult> validate() async { Future<ValidationResult> validate() async {
final List<ValidationMessage> messages = <ValidationMessage>[]; final List<ValidationMessage> messages = <ValidationMessage>[];
final String cfgAndroidStudio = config.getValue('android-studio-dir') as String; final String cfgAndroidStudio = globals.config.getValue('android-studio-dir') as String;
if (cfgAndroidStudio != null) { if (cfgAndroidStudio != null) {
messages.add(ValidationMessage.error(userMessages.androidStudioMissing(cfgAndroidStudio))); messages.add(ValidationMessage.error(userMessages.androidStudioMissing(cfgAndroidStudio)));
} }
......
...@@ -7,15 +7,13 @@ import 'dart:async'; ...@@ -7,15 +7,13 @@ import 'dart:async';
import '../base/common.dart'; import '../base/common.dart';
import '../base/context.dart'; import '../base/context.dart';
import '../base/io.dart'; import '../base/io.dart';
import '../base/platform.dart';
import '../base/process.dart'; import '../base/process.dart';
import '../base/process_manager.dart';
import '../base/user_messages.dart'; import '../base/user_messages.dart';
import '../base/utils.dart'; import '../base/utils.dart';
import '../base/version.dart'; import '../base/version.dart';
import '../convert.dart'; import '../convert.dart';
import '../doctor.dart'; import '../doctor.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import 'android_sdk.dart'; import 'android_sdk.dart';
const int kAndroidSdkMinVersion = 28; const int kAndroidSdkMinVersion = 28;
...@@ -74,20 +72,20 @@ class AndroidValidator extends DoctorValidator { ...@@ -74,20 +72,20 @@ class AndroidValidator extends DoctorValidator {
Future<bool> _checkJavaVersion(String javaBinary, List<ValidationMessage> messages) async { Future<bool> _checkJavaVersion(String javaBinary, List<ValidationMessage> messages) async {
_task = 'Checking Java status'; _task = 'Checking Java status';
try { try {
if (!processManager.canRun(javaBinary)) { if (!globals.processManager.canRun(javaBinary)) {
messages.add(ValidationMessage.error(userMessages.androidCantRunJavaBinary(javaBinary))); messages.add(ValidationMessage.error(userMessages.androidCantRunJavaBinary(javaBinary)));
return false; return false;
} }
String javaVersionText; String javaVersionText;
try { try {
printTrace('java -version'); globals.printTrace('java -version');
final ProcessResult result = await processManager.run(<String>[javaBinary, '-version']); final ProcessResult result = await globals.processManager.run(<String>[javaBinary, '-version']);
if (result.exitCode == 0) { if (result.exitCode == 0) {
final List<String> versionLines = (result.stderr as String).split('\n'); final List<String> versionLines = (result.stderr as String).split('\n');
javaVersionText = versionLines.length >= 2 ? versionLines[1] : versionLines[0]; javaVersionText = versionLines.length >= 2 ? versionLines[1] : versionLines[0];
} }
} catch (error) { } catch (error) {
printTrace(error.toString()); globals.printTrace(error.toString());
} }
if (javaVersionText == null || javaVersionText.isEmpty) { if (javaVersionText == null || javaVersionText.isEmpty) {
// Could not determine the java version. // Could not determine the java version.
...@@ -112,8 +110,8 @@ class AndroidValidator extends DoctorValidator { ...@@ -112,8 +110,8 @@ class AndroidValidator extends DoctorValidator {
if (androidSdk == null) { if (androidSdk == null) {
// No Android SDK found. // No Android SDK found.
if (platform.environment.containsKey(kAndroidHome)) { if (globals.platform.environment.containsKey(kAndroidHome)) {
final String androidHomeDir = platform.environment[kAndroidHome]; final String androidHomeDir = globals.platform.environment[kAndroidHome];
messages.add(ValidationMessage.error(userMessages.androidBadSdkDir(kAndroidHome, androidHomeDir))); messages.add(ValidationMessage.error(userMessages.androidBadSdkDir(kAndroidHome, androidHomeDir)));
} else { } else {
messages.add(ValidationMessage.error(userMessages.androidMissingSdkInstructions(kAndroidHome))); messages.add(ValidationMessage.error(userMessages.androidMissingSdkInstructions(kAndroidHome)));
...@@ -149,12 +147,12 @@ class AndroidValidator extends DoctorValidator { ...@@ -149,12 +147,12 @@ class AndroidValidator extends DoctorValidator {
messages.add(ValidationMessage.error(userMessages.androidMissingSdkInstructions(kAndroidHome))); messages.add(ValidationMessage.error(userMessages.androidMissingSdkInstructions(kAndroidHome)));
} }
if (platform.environment.containsKey(kAndroidHome)) { if (globals.platform.environment.containsKey(kAndroidHome)) {
final String androidHomeDir = platform.environment[kAndroidHome]; final String androidHomeDir = globals.platform.environment[kAndroidHome];
messages.add(ValidationMessage('$kAndroidHome = $androidHomeDir')); messages.add(ValidationMessage('$kAndroidHome = $androidHomeDir'));
} }
if (platform.environment.containsKey(kAndroidSdkRoot)) { if (globals.platform.environment.containsKey(kAndroidSdkRoot)) {
final String androidSdkRoot = platform.environment[kAndroidSdkRoot]; final String androidSdkRoot = globals.platform.environment[kAndroidSdkRoot];
messages.add(ValidationMessage('$kAndroidSdkRoot = $androidSdkRoot')); messages.add(ValidationMessage('$kAndroidSdkRoot = $androidSdkRoot'));
} }
...@@ -229,18 +227,18 @@ class AndroidLicenseValidator extends DoctorValidator { ...@@ -229,18 +227,18 @@ class AndroidLicenseValidator extends DoctorValidator {
if (javaBinary == null) { if (javaBinary == null) {
return false; return false;
} }
if (!processManager.canRun(javaBinary)) { if (!globals.processManager.canRun(javaBinary)) {
return false; return false;
} }
String javaVersion; String javaVersion;
try { try {
final ProcessResult result = await processManager.run(<String>[javaBinary, '-version']); final ProcessResult result = await globals.processManager.run(<String>[javaBinary, '-version']);
if (result.exitCode == 0) { if (result.exitCode == 0) {
final List<String> versionLines = (result.stderr as String).split('\n'); final List<String> versionLines = (result.stderr as String).split('\n');
javaVersion = versionLines.length >= 2 ? versionLines[1] : versionLines[0]; javaVersion = versionLines.length >= 2 ? versionLines[1] : versionLines[0];
} }
} catch (error) { } catch (error) {
printTrace(error.toString()); globals.printTrace(error.toString());
} }
if (javaVersion == null) { if (javaVersion == null) {
// Could not determine the java version. // Could not determine the java version.
...@@ -295,7 +293,7 @@ class AndroidLicenseValidator extends DoctorValidator { ...@@ -295,7 +293,7 @@ class AndroidLicenseValidator extends DoctorValidator {
await Future.wait<void>(<Future<void>>[output, errors]); await Future.wait<void>(<Future<void>>[output, errors]);
return status ?? LicensesAccepted.unknown; return status ?? LicensesAccepted.unknown;
} on ProcessException catch (e) { } on ProcessException catch (e) {
printTrace('Failed to run Android sdk manager: $e'); globals.printTrace('Failed to run Android sdk manager: $e');
return LicensesAccepted.unknown; return LicensesAccepted.unknown;
} }
} }
...@@ -303,7 +301,7 @@ class AndroidLicenseValidator extends DoctorValidator { ...@@ -303,7 +301,7 @@ class AndroidLicenseValidator extends DoctorValidator {
/// Run the Android SDK manager tool in order to accept SDK licenses. /// Run the Android SDK manager tool in order to accept SDK licenses.
static Future<bool> runLicenseManager() async { static Future<bool> runLicenseManager() async {
if (androidSdk == null) { if (androidSdk == null) {
printStatus(userMessages.androidSdkShort); globals.printStatus(userMessages.androidSdkShort);
return false; return false;
} }
...@@ -345,6 +343,6 @@ class AndroidLicenseValidator extends DoctorValidator { ...@@ -345,6 +343,6 @@ class AndroidLicenseValidator extends DoctorValidator {
static bool _canRunSdkManager() { static bool _canRunSdkManager() {
assert(androidSdk != null); assert(androidSdk != null);
final String sdkManagerPath = androidSdk.sdkManagerPath; final String sdkManagerPath = androidSdk.sdkManagerPath;
return processManager.canRun(sdkManagerPath); return globals.processManager.canRun(sdkManagerPath);
} }
} }
...@@ -6,7 +6,7 @@ import 'package:meta/meta.dart'; ...@@ -6,7 +6,7 @@ import 'package:meta/meta.dart';
import '../base/process.dart'; import '../base/process.dart';
import '../base/terminal.dart'; import '../base/terminal.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import '../project.dart'; import '../project.dart';
import '../reporting/reporting.dart'; import '../reporting/reporting.dart';
import 'gradle_utils.dart'; import 'gradle_utils.dart';
...@@ -85,8 +85,8 @@ final GradleHandledError permissionDeniedErrorHandler = GradleHandledError( ...@@ -85,8 +85,8 @@ final GradleHandledError permissionDeniedErrorHandler = GradleHandledError(
bool usesAndroidX, bool usesAndroidX,
bool shouldBuildPluginAsAar, bool shouldBuildPluginAsAar,
}) async { }) async {
printStatus('$warningMark Gradle does not have execution permission.', emphasis: true); globals.printStatus('$warningMark Gradle does not have execution permission.', emphasis: true);
printStatus( globals.printStatus(
'You should change the ownership of the project directory to your user, ' 'You should change the ownership of the project directory to your user, '
'or move the project to a directory with execute permissions.', 'or move the project to a directory with execute permissions.',
indent: 4 indent: 4
...@@ -115,7 +115,7 @@ final GradleHandledError networkErrorHandler = GradleHandledError( ...@@ -115,7 +115,7 @@ final GradleHandledError networkErrorHandler = GradleHandledError(
bool usesAndroidX, bool usesAndroidX,
bool shouldBuildPluginAsAar, bool shouldBuildPluginAsAar,
}) async { }) async {
printError( globals.printError(
'$warningMark Gradle threw an error while trying to update itself. ' '$warningMark Gradle threw an error while trying to update itself. '
'Retrying the update...' 'Retrying the update...'
); );
...@@ -136,9 +136,9 @@ final GradleHandledError r8FailureHandler = GradleHandledError( ...@@ -136,9 +136,9 @@ final GradleHandledError r8FailureHandler = GradleHandledError(
bool usesAndroidX, bool usesAndroidX,
bool shouldBuildPluginAsAar, bool shouldBuildPluginAsAar,
}) async { }) async {
printStatus('$warningMark The shrinker may have failed to optimize the Java bytecode.', emphasis: true); globals.printStatus('$warningMark The shrinker may have failed to optimize the Java bytecode.', emphasis: true);
printStatus('To disable the shrinker, pass the `--no-shrink` flag to this command.', indent: 4); globals.printStatus('To disable the shrinker, pass the `--no-shrink` flag to this command.', indent: 4);
printStatus('To learn more, see: https://developer.android.com/studio/build/shrink-code', indent: 4); globals.printStatus('To learn more, see: https://developer.android.com/studio/build/shrink-code', indent: 4);
return GradleBuildStatus.exit; return GradleBuildStatus.exit;
}, },
eventLabel: 'r8', eventLabel: 'r8',
...@@ -187,7 +187,7 @@ final GradleHandledError androidXFailureHandler = GradleHandledError( ...@@ -187,7 +187,7 @@ final GradleHandledError androidXFailureHandler = GradleHandledError(
if (hasPlugins && !usesAndroidX) { if (hasPlugins && !usesAndroidX) {
// If the app isn't using AndroidX, then the app is likely using // If the app isn't using AndroidX, then the app is likely using
// a plugin already migrated to AndroidX. // a plugin already migrated to AndroidX.
printStatus( globals.printStatus(
'AndroidX incompatibilities may have caused this build to fail. ' 'AndroidX incompatibilities may have caused this build to fail. '
'Please migrate your app to AndroidX. See https://goo.gl/CP92wY.' 'Please migrate your app to AndroidX. See https://goo.gl/CP92wY.'
); );
...@@ -206,7 +206,7 @@ final GradleHandledError androidXFailureHandler = GradleHandledError( ...@@ -206,7 +206,7 @@ final GradleHandledError androidXFailureHandler = GradleHandledError(
).send(); ).send();
} }
if (hasPlugins && usesAndroidX && !shouldBuildPluginAsAar) { if (hasPlugins && usesAndroidX && !shouldBuildPluginAsAar) {
printStatus( globals.printStatus(
'The built failed likely due to AndroidX incompatibilities in a plugin. ' 'The built failed likely due to AndroidX incompatibilities in a plugin. '
'The tool is about to try using Jetfier to solve the incompatibility.' 'The tool is about to try using Jetfier to solve the incompatibility.'
); );
...@@ -242,7 +242,7 @@ final GradleHandledError licenseNotAcceptedHandler = GradleHandledError( ...@@ -242,7 +242,7 @@ final GradleHandledError licenseNotAcceptedHandler = GradleHandledError(
final RegExp licenseFailure = RegExp(licenseNotAcceptedMatcher, multiLine: true); final RegExp licenseFailure = RegExp(licenseNotAcceptedMatcher, multiLine: true);
assert(licenseFailure != null); assert(licenseFailure != null);
final Match licenseMatch = licenseFailure.firstMatch(line); final Match licenseMatch = licenseFailure.firstMatch(line);
printStatus( globals.printStatus(
'$warningMark Unable to download needed Android SDK components, as the ' '$warningMark Unable to download needed Android SDK components, as the '
'following licenses have not been accepted:\n' 'following licenses have not been accepted:\n'
'${licenseMatch.group(1)}\n\n' '${licenseMatch.group(1)}\n\n'
...@@ -303,18 +303,18 @@ final GradleHandledError flavorUndefinedHandler = GradleHandledError( ...@@ -303,18 +303,18 @@ final GradleHandledError flavorUndefinedHandler = GradleHandledError(
} }
} }
} }
printStatus( globals.printStatus(
'\n$warningMark Gradle project does not define a task suitable ' '\n$warningMark Gradle project does not define a task suitable '
'for the requested build.' 'for the requested build.'
); );
if (productFlavors.isEmpty) { if (productFlavors.isEmpty) {
printStatus( globals.printStatus(
'The android/app/build.gradle file does not define ' 'The android/app/build.gradle file does not define '
'any custom product flavors. ' 'any custom product flavors. '
'You cannot use the --flavor option.' 'You cannot use the --flavor option.'
); );
} else { } else {
printStatus( globals.printStatus(
'The android/app/build.gradle file defines product ' 'The android/app/build.gradle file defines product '
'flavors: ${productFlavors.join(', ')} ' 'flavors: ${productFlavors.join(', ')} '
'You must specify a --flavor option to select one of them.' 'You must specify a --flavor option to select one of them.'
......
...@@ -9,13 +9,12 @@ import '../base/common.dart'; ...@@ -9,13 +9,12 @@ import '../base/common.dart';
import '../base/context.dart'; import '../base/context.dart';
import '../base/file_system.dart'; import '../base/file_system.dart';
import '../base/os.dart'; import '../base/os.dart';
import '../base/platform.dart';
import '../base/terminal.dart'; import '../base/terminal.dart';
import '../base/utils.dart'; import '../base/utils.dart';
import '../base/version.dart'; import '../base/version.dart';
import '../build_info.dart'; import '../build_info.dart';
import '../cache.dart'; import '../cache.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import '../project.dart'; import '../project.dart';
import '../reporting/reporting.dart'; import '../reporting/reporting.dart';
import 'android_sdk.dart'; import 'android_sdk.dart';
...@@ -23,7 +22,7 @@ import 'android_studio.dart'; ...@@ -23,7 +22,7 @@ import 'android_studio.dart';
/// The environment variables needed to run Gradle. /// The environment variables needed to run Gradle.
Map<String, String> get gradleEnvironment { Map<String, String> get gradleEnvironment {
final Map<String, String> environment = Map<String, String>.from(platform.environment); final Map<String, String> environment = Map<String, String>.from(globals.platform.environment);
if (javaPath != null) { if (javaPath != null) {
// Use java bundled with Android Studio. // Use java bundled with Android Studio.
environment['JAVA_HOME'] = javaPath; environment['JAVA_HOME'] = javaPath;
...@@ -50,10 +49,10 @@ class GradleUtils { ...@@ -50,10 +49,10 @@ class GradleUtils {
gradleUtils.injectGradleWrapperIfNeeded(androidDir); gradleUtils.injectGradleWrapperIfNeeded(androidDir);
final File gradle = androidDir.childFile( final File gradle = androidDir.childFile(
platform.isWindows ? 'gradlew.bat' : 'gradlew', globals.platform.isWindows ? 'gradlew.bat' : 'gradlew',
); );
if (gradle.existsSync()) { if (gradle.existsSync()) {
printTrace('Using gradle from ${gradle.absolute.path}.'); globals.printTrace('Using gradle from ${gradle.absolute.path}.');
// If the Gradle executable doesn't have execute permission, // If the Gradle executable doesn't have execute permission,
// then attempt to set it. // then attempt to set it.
_giveExecutePermissionIfNeeded(gradle); _giveExecutePermissionIfNeeded(gradle);
...@@ -79,10 +78,10 @@ class GradleUtils { ...@@ -79,10 +78,10 @@ class GradleUtils {
} }
final String propertiesContent = gradleProperties.readAsStringSync(); final String propertiesContent = gradleProperties.readAsStringSync();
if (propertiesContent.contains('android.enableR8')) { if (propertiesContent.contains('android.enableR8')) {
printTrace('gradle.properties already sets `android.enableR8`'); globals.printTrace('gradle.properties already sets `android.enableR8`');
return; return;
} }
printTrace('set `android.enableR8=true` in gradle.properties'); globals.printTrace('set `android.enableR8=true` in gradle.properties');
try { try {
if (propertiesContent.isNotEmpty && !propertiesContent.endsWith('\n')) { if (propertiesContent.isNotEmpty && !propertiesContent.endsWith('\n')) {
// Add a new line if the file doesn't end with a new line. // Add a new line if the file doesn't end with a new line.
...@@ -100,7 +99,7 @@ class GradleUtils { ...@@ -100,7 +99,7 @@ class GradleUtils {
/// Injects the Gradle wrapper files if any of these files don't exist in [directory]. /// Injects the Gradle wrapper files if any of these files don't exist in [directory].
void injectGradleWrapperIfNeeded(Directory directory) { void injectGradleWrapperIfNeeded(Directory directory) {
copyDirectorySync( copyDirectorySync(
cache.getArtifactDirectory('gradle_wrapper'), globals.cache.getArtifactDirectory('gradle_wrapper'),
directory, directory,
shouldCopyFile: (File sourceFile, File destinationFile) { shouldCopyFile: (File sourceFile, File destinationFile) {
// Don't override the existing files in the project. // Don't override the existing files in the project.
...@@ -114,7 +113,7 @@ class GradleUtils { ...@@ -114,7 +113,7 @@ class GradleUtils {
); );
// Add the `gradle-wrapper.properties` file if it doesn't exist. // Add the `gradle-wrapper.properties` file if it doesn't exist.
final File propertiesFile = directory.childFile( final File propertiesFile = directory.childFile(
fs.path.join('gradle', 'wrapper', 'gradle-wrapper.properties')); globals.fs.path.join('gradle', 'wrapper', 'gradle-wrapper.properties'));
if (!propertiesFile.existsSync()) { if (!propertiesFile.existsSync()) {
final String gradleVersion = getGradleVersionForAndroidPlugin(directory); final String gradleVersion = getGradleVersionForAndroidPlugin(directory);
propertiesFile.writeAsStringSync(''' propertiesFile.writeAsStringSync('''
...@@ -157,7 +156,7 @@ const int _kExecPermissionMask = 0x49; // a+x ...@@ -157,7 +156,7 @@ const int _kExecPermissionMask = 0x49; // a+x
bool _hasAllExecutableFlagSet(File executable) { bool _hasAllExecutableFlagSet(File executable) {
final FileStat stat = executable.statSync(); final FileStat stat = executable.statSync();
assert(stat.type != FileSystemEntityType.notFound); assert(stat.type != FileSystemEntityType.notFound);
printTrace('${executable.path} mode: ${stat.mode} ${stat.modeString()}.'); globals.printTrace('${executable.path} mode: ${stat.mode} ${stat.modeString()}.');
return stat.mode & _kExecPermissionMask == _kExecPermissionMask; return stat.mode & _kExecPermissionMask == _kExecPermissionMask;
} }
...@@ -165,14 +164,14 @@ bool _hasAllExecutableFlagSet(File executable) { ...@@ -165,14 +164,14 @@ bool _hasAllExecutableFlagSet(File executable) {
bool _hasAnyExecutableFlagSet(File executable) { bool _hasAnyExecutableFlagSet(File executable) {
final FileStat stat = executable.statSync(); final FileStat stat = executable.statSync();
assert(stat.type != FileSystemEntityType.notFound); assert(stat.type != FileSystemEntityType.notFound);
printTrace('${executable.path} mode: ${stat.mode} ${stat.modeString()}.'); globals.printTrace('${executable.path} mode: ${stat.mode} ${stat.modeString()}.');
return stat.mode & _kExecPermissionMask != 0; return stat.mode & _kExecPermissionMask != 0;
} }
/// Gives execute permission to [executable] if it doesn't have it already. /// Gives execute permission to [executable] if it doesn't have it already.
void _giveExecutePermissionIfNeeded(File executable) { void _giveExecutePermissionIfNeeded(File executable) {
if (!_hasAllExecutableFlagSet(executable)) { if (!_hasAllExecutableFlagSet(executable)) {
printTrace('Trying to give execute permission to ${executable.path}.'); globals.printTrace('Trying to give execute permission to ${executable.path}.');
os.makeExecutable(executable); os.makeExecutable(executable);
} }
} }
......
...@@ -8,7 +8,6 @@ import 'package:meta/meta.dart'; ...@@ -8,7 +8,6 @@ import 'package:meta/meta.dart';
import 'base/build.dart'; import 'base/build.dart';
import 'base/common.dart'; import 'base/common.dart';
import 'base/file_system.dart';
import 'base/io.dart'; import 'base/io.dart';
import 'base/logger.dart'; import 'base/logger.dart';
import 'base/process.dart'; import 'base/process.dart';
...@@ -16,7 +15,7 @@ import 'build_info.dart'; ...@@ -16,7 +15,7 @@ import 'build_info.dart';
import 'build_system/build_system.dart'; import 'build_system/build_system.dart';
import 'build_system/targets/dart.dart'; import 'build_system/targets/dart.dart';
import 'dart/package_map.dart'; import 'dart/package_map.dart';
import 'globals.dart'; import 'globals.dart' as globals;
import 'ios/bitcode.dart'; import 'ios/bitcode.dart';
import 'project.dart'; import 'project.dart';
...@@ -61,8 +60,8 @@ class AotBuilder { ...@@ -61,8 +60,8 @@ class AotBuilder {
Status status; Status status;
if (!quiet) { if (!quiet) {
final String typeName = artifacts.getEngineType(platform, buildMode); final String typeName = globals.artifacts.getEngineType(platform, buildMode);
status = logger.startProgress( status = globals.logger.startProgress(
'Building AOT snapshot in ${getFriendlyModeName(buildMode)} mode ($typeName)...', 'Building AOT snapshot in ${getFriendlyModeName(buildMode)} mode ($typeName)...',
timeout: timeoutConfiguration.slowOperation, timeout: timeoutConfiguration.slowOperation,
); );
...@@ -91,7 +90,7 @@ class AotBuilder { ...@@ -91,7 +90,7 @@ class AotBuilder {
// Determine which iOS architectures to build for. // Determine which iOS architectures to build for.
final Map<DarwinArch, String> iosBuilds = <DarwinArch, String>{}; final Map<DarwinArch, String> iosBuilds = <DarwinArch, String>{};
for (DarwinArch arch in iosBuildArchs) { for (DarwinArch arch in iosBuildArchs) {
iosBuilds[arch] = fs.path.join(outputPath, getNameForDarwinArch(arch)); iosBuilds[arch] = globals.fs.path.join(outputPath, getNameForDarwinArch(arch));
} }
// Generate AOT snapshot and compile to arch-specific App.framework. // Generate AOT snapshot and compile to arch-specific App.framework.
...@@ -115,14 +114,14 @@ class AotBuilder { ...@@ -115,14 +114,14 @@ class AotBuilder {
// Merge arch-specific App.frameworks into a multi-arch App.framework. // Merge arch-specific App.frameworks into a multi-arch App.framework.
if ((await Future.wait<int>(exitCodes.values)).every((int buildExitCode) => buildExitCode == 0)) { if ((await Future.wait<int>(exitCodes.values)).every((int buildExitCode) => buildExitCode == 0)) {
final Iterable<String> dylibs = iosBuilds.values.map<String>( final Iterable<String> dylibs = iosBuilds.values.map<String>(
(String outputDir) => fs.path.join(outputDir, 'App.framework', 'App')); (String outputDir) => globals.fs.path.join(outputDir, 'App.framework', 'App'));
fs.directory(fs.path.join(outputPath, 'App.framework'))..createSync(); globals.fs.directory(globals.fs.path.join(outputPath, 'App.framework'))..createSync();
await processUtils.run( await processUtils.run(
<String>[ <String>[
'lipo', 'lipo',
...dylibs, ...dylibs,
'-create', '-create',
'-output', fs.path.join(outputPath, 'App.framework', 'App'), '-output', globals.fs.path.join(outputPath, 'App.framework', 'App'),
], ],
throwOnError: true, throwOnError: true,
); );
...@@ -130,7 +129,7 @@ class AotBuilder { ...@@ -130,7 +129,7 @@ class AotBuilder {
status?.cancel(); status?.cancel();
exitCodes.forEach((DarwinArch iosArch, Future<int> exitCodeFuture) async { exitCodes.forEach((DarwinArch iosArch, Future<int> exitCodeFuture) async {
final int buildExitCode = await exitCodeFuture; final int buildExitCode = await exitCodeFuture;
printError('Snapshotting ($iosArch) exited with non-zero exit code: $buildExitCode'); globals.printError('Snapshotting ($iosArch) exited with non-zero exit code: $buildExitCode');
}); });
} }
} else { } else {
...@@ -152,7 +151,7 @@ class AotBuilder { ...@@ -152,7 +151,7 @@ class AotBuilder {
} on ProcessException catch (error) { } on ProcessException catch (error) {
// Catch the String exceptions thrown from the `runSync` methods below. // Catch the String exceptions thrown from the `runSync` methods below.
status?.cancel(); status?.cancel();
printError(error.toString()); globals.printError(error.toString());
return; return;
} }
status?.stop(); status?.stop();
...@@ -161,11 +160,11 @@ class AotBuilder { ...@@ -161,11 +160,11 @@ class AotBuilder {
throwToolExit(null); throwToolExit(null);
} }
final String builtMessage = 'Built to $outputPath${fs.path.separator}.'; final String builtMessage = 'Built to $outputPath${globals.fs.path.separator}.';
if (quiet) { if (quiet) {
printTrace(builtMessage); globals.printTrace(builtMessage);
} else { } else {
printStatus(builtMessage); globals.printStatus(builtMessage);
} }
return; return;
} }
...@@ -199,8 +198,8 @@ class AotBuilder { ...@@ -199,8 +198,8 @@ class AotBuilder {
}) async { }) async {
Status status; Status status;
if (!quiet) { if (!quiet) {
final String typeName = artifacts.getEngineType(targetPlatform, buildMode); final String typeName = globals.artifacts.getEngineType(targetPlatform, buildMode);
status = logger.startProgress( status = globals.logger.startProgress(
'Building AOT snapshot in ${getFriendlyModeName(buildMode)} mode ($typeName)...', 'Building AOT snapshot in ${getFriendlyModeName(buildMode)} mode ($typeName)...',
timeout: timeoutConfiguration.slowOperation, timeout: timeoutConfiguration.slowOperation,
); );
...@@ -213,7 +212,7 @@ class AotBuilder { ...@@ -213,7 +212,7 @@ class AotBuilder {
final BuildResult result = await buildSystem.build(target, Environment( final BuildResult result = await buildSystem.build(target, Environment(
projectDir: flutterProject.directory, projectDir: flutterProject.directory,
outputDir: fs.directory(outputDir), outputDir: globals.fs.directory(outputDir),
buildDir: flutterProject.directory buildDir: flutterProject.directory
.childDirectory('.dart_tool') .childDirectory('.dart_tool')
.childDirectory('flutter_build'), .childDirectory('flutter_build'),
...@@ -226,7 +225,7 @@ class AotBuilder { ...@@ -226,7 +225,7 @@ class AotBuilder {
status?.stop(); status?.stop();
if (!result.success) { if (!result.success) {
for (ExceptionMeasurement measurement in result.exceptions.values) { for (ExceptionMeasurement measurement in result.exceptions.values) {
printError('Target ${measurement.target} failed: ${measurement.exception}', globals.printError('Target ${measurement.target} failed: ${measurement.exception}',
stackTrace: measurement.fatal stackTrace: measurement.fatal
? measurement.stackTrace ? measurement.stackTrace
: null, : null,
...@@ -234,11 +233,11 @@ class AotBuilder { ...@@ -234,11 +233,11 @@ class AotBuilder {
} }
throwToolExit('Failed to build aot.'); throwToolExit('Failed to build aot.');
} }
final String builtMessage = 'Built to $outputDir${fs.path.separator}.'; final String builtMessage = 'Built to $outputDir${globals.fs.path.separator}.';
if (quiet) { if (quiet) {
printTrace(builtMessage); globals.printTrace(builtMessage);
} else { } else {
printStatus(builtMessage); globals.printStatus(builtMessage);
} }
} }
} }
...@@ -19,7 +19,7 @@ import 'base/process.dart'; ...@@ -19,7 +19,7 @@ import 'base/process.dart';
import 'base/user_messages.dart'; import 'base/user_messages.dart';
import 'build_info.dart'; import 'build_info.dart';
import 'fuchsia/application_package.dart'; import 'fuchsia/application_package.dart';
import 'globals.dart'; import 'globals.dart' as globals;
import 'ios/plist_parser.dart'; import 'ios/plist_parser.dart';
import 'linux/application_package.dart'; import 'linux/application_package.dart';
import 'macos/application_package.dart'; import 'macos/application_package.dart';
...@@ -112,7 +112,7 @@ class AndroidApk extends ApplicationPackage { ...@@ -112,7 +112,7 @@ class AndroidApk extends ApplicationPackage {
factory AndroidApk.fromApk(File apk) { factory AndroidApk.fromApk(File apk) {
final String aaptPath = androidSdk?.latestVersion?.aaptPath; final String aaptPath = androidSdk?.latestVersion?.aaptPath;
if (aaptPath == null) { if (aaptPath == null) {
printError(userMessages.aaptNotFound); globals.printError(userMessages.aaptNotFound);
return null; return null;
} }
...@@ -129,19 +129,19 @@ class AndroidApk extends ApplicationPackage { ...@@ -129,19 +129,19 @@ class AndroidApk extends ApplicationPackage {
throwOnError: true, throwOnError: true,
).stdout.trim(); ).stdout.trim();
} on ProcessException catch (error) { } on ProcessException catch (error) {
printError('Failed to extract manifest from APK: $error.'); globals.printError('Failed to extract manifest from APK: $error.');
return null; return null;
} }
final ApkManifestData data = ApkManifestData.parseFromXmlDump(apptStdout); final ApkManifestData data = ApkManifestData.parseFromXmlDump(apptStdout);
if (data == null) { if (data == null) {
printError('Unable to read manifest info from ${apk.path}.'); globals.printError('Unable to read manifest info from ${apk.path}.');
return null; return null;
} }
if (data.packageName == null || data.launchableActivityName == null) { if (data.packageName == null || data.launchableActivityName == null) {
printError('Unable to read manifest info from ${apk.path}.'); globals.printError('Unable to read manifest info from ${apk.path}.');
return null; return null;
} }
...@@ -177,14 +177,14 @@ class AndroidApk extends ApplicationPackage { ...@@ -177,14 +177,14 @@ class AndroidApk extends ApplicationPackage {
// command will grab a new AndroidApk after building, to get the updated // command will grab a new AndroidApk after building, to get the updated
// IDs. // IDs.
} else { } else {
apkFile = fs.file(fs.path.join(getAndroidBuildDirectory(), 'app.apk')); apkFile = globals.fs.file(globals.fs.path.join(getAndroidBuildDirectory(), 'app.apk'));
} }
final File manifest = androidProject.appManifestFile; final File manifest = androidProject.appManifestFile;
if (!manifest.existsSync()) { if (!manifest.existsSync()) {
printError('AndroidManifest.xml could not be found.'); globals.printError('AndroidManifest.xml could not be found.');
printError('Please check ${manifest.path} for errors.'); globals.printError('Please check ${manifest.path} for errors.');
return null; return null;
} }
...@@ -195,19 +195,19 @@ class AndroidApk extends ApplicationPackage { ...@@ -195,19 +195,19 @@ class AndroidApk extends ApplicationPackage {
} on xml.XmlParserException catch (exception) { } on xml.XmlParserException catch (exception) {
String manifestLocation; String manifestLocation;
if (androidProject.isUsingGradle) { if (androidProject.isUsingGradle) {
manifestLocation = fs.path.join(androidProject.hostAppGradleRoot.path, 'app', 'src', 'main', 'AndroidManifest.xml'); manifestLocation = globals.fs.path.join(androidProject.hostAppGradleRoot.path, 'app', 'src', 'main', 'AndroidManifest.xml');
} else { } else {
manifestLocation = fs.path.join(androidProject.hostAppGradleRoot.path, 'AndroidManifest.xml'); manifestLocation = globals.fs.path.join(androidProject.hostAppGradleRoot.path, 'AndroidManifest.xml');
} }
printError('AndroidManifest.xml is not a valid XML document.'); globals.printError('AndroidManifest.xml is not a valid XML document.');
printError('Please check $manifestLocation for errors.'); globals.printError('Please check $manifestLocation for errors.');
throwToolExit('XML Parser error message: ${exception.toString()}'); throwToolExit('XML Parser error message: ${exception.toString()}');
} }
final Iterable<xml.XmlElement> manifests = document.findElements('manifest'); final Iterable<xml.XmlElement> manifests = document.findElements('manifest');
if (manifests.isEmpty) { if (manifests.isEmpty) {
printError('AndroidManifest.xml has no manifest element.'); globals.printError('AndroidManifest.xml has no manifest element.');
printError('Please check ${manifest.path} for errors.'); globals.printError('Please check ${manifest.path} for errors.');
return null; return null;
} }
final String packageId = manifests.first.getAttribute('package'); final String packageId = manifests.first.getAttribute('package');
...@@ -243,8 +243,8 @@ class AndroidApk extends ApplicationPackage { ...@@ -243,8 +243,8 @@ class AndroidApk extends ApplicationPackage {
} }
if (packageId == null || launchActivity == null) { if (packageId == null || launchActivity == null) {
printError('package identifier or launch activity not found.'); globals.printError('package identifier or launch activity not found.');
printError('Please check ${manifest.path} for errors.'); globals.printError('Please check ${manifest.path} for errors.');
return null; return null;
} }
...@@ -271,46 +271,46 @@ abstract class IOSApp extends ApplicationPackage { ...@@ -271,46 +271,46 @@ abstract class IOSApp extends ApplicationPackage {
/// Creates a new IOSApp from an existing app bundle or IPA. /// Creates a new IOSApp from an existing app bundle or IPA.
factory IOSApp.fromPrebuiltApp(FileSystemEntity applicationBinary) { factory IOSApp.fromPrebuiltApp(FileSystemEntity applicationBinary) {
final FileSystemEntityType entityType = fs.typeSync(applicationBinary.path); final FileSystemEntityType entityType = globals.fs.typeSync(applicationBinary.path);
if (entityType == FileSystemEntityType.notFound) { if (entityType == FileSystemEntityType.notFound) {
printError( globals.printError(
'File "${applicationBinary.path}" does not exist. Use an app bundle or an ipa.'); 'File "${applicationBinary.path}" does not exist. Use an app bundle or an ipa.');
return null; return null;
} }
Directory bundleDir; Directory bundleDir;
if (entityType == FileSystemEntityType.directory) { if (entityType == FileSystemEntityType.directory) {
final Directory directory = fs.directory(applicationBinary); final Directory directory = globals.fs.directory(applicationBinary);
if (!_isBundleDirectory(directory)) { if (!_isBundleDirectory(directory)) {
printError('Folder "${applicationBinary.path}" is not an app bundle.'); globals.printError('Folder "${applicationBinary.path}" is not an app bundle.');
return null; return null;
} }
bundleDir = fs.directory(applicationBinary); bundleDir = globals.fs.directory(applicationBinary);
} else { } else {
// Try to unpack as an ipa. // Try to unpack as an ipa.
final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_app.'); final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_app.');
addShutdownHook(() async { addShutdownHook(() async {
await tempDir.delete(recursive: true); await tempDir.delete(recursive: true);
}, ShutdownStage.STILL_RECORDING); }, ShutdownStage.STILL_RECORDING);
os.unzip(fs.file(applicationBinary), tempDir); os.unzip(globals.fs.file(applicationBinary), tempDir);
final Directory payloadDir = fs.directory( final Directory payloadDir = globals.fs.directory(
fs.path.join(tempDir.path, 'Payload'), globals.fs.path.join(tempDir.path, 'Payload'),
); );
if (!payloadDir.existsSync()) { if (!payloadDir.existsSync()) {
printError( globals.printError(
'Invalid prebuilt iOS ipa. Does not contain a "Payload" directory.'); 'Invalid prebuilt iOS ipa. Does not contain a "Payload" directory.');
return null; return null;
} }
try { try {
bundleDir = payloadDir.listSync().whereType<Directory>().singleWhere(_isBundleDirectory); bundleDir = payloadDir.listSync().whereType<Directory>().singleWhere(_isBundleDirectory);
} on StateError { } on StateError {
printError( globals.printError(
'Invalid prebuilt iOS ipa. Does not contain a single app bundle.'); 'Invalid prebuilt iOS ipa. Does not contain a single app bundle.');
return null; return null;
} }
} }
final String plistPath = fs.path.join(bundleDir.path, 'Info.plist'); final String plistPath = globals.fs.path.join(bundleDir.path, 'Info.plist');
if (!fs.file(plistPath).existsSync()) { if (!globals.fs.file(plistPath).existsSync()) {
printError('Invalid prebuilt iOS app. Does not contain Info.plist.'); globals.printError('Invalid prebuilt iOS app. Does not contain Info.plist.');
return null; return null;
} }
final String id = PlistParser.instance.getValueFromFile( final String id = PlistParser.instance.getValueFromFile(
...@@ -318,13 +318,13 @@ abstract class IOSApp extends ApplicationPackage { ...@@ -318,13 +318,13 @@ abstract class IOSApp extends ApplicationPackage {
PlistParser.kCFBundleIdentifierKey, PlistParser.kCFBundleIdentifierKey,
); );
if (id == null) { if (id == null) {
printError('Invalid prebuilt iOS app. Info.plist does not contain bundle identifier'); globals.printError('Invalid prebuilt iOS app. Info.plist does not contain bundle identifier');
return null; return null;
} }
return PrebuiltIOSApp( return PrebuiltIOSApp(
bundleDir: bundleDir, bundleDir: bundleDir,
bundleName: fs.path.basename(bundleDir.path), bundleName: globals.fs.path.basename(bundleDir.path),
projectBundleId: id, projectBundleId: id,
); );
} }
...@@ -339,11 +339,11 @@ abstract class IOSApp extends ApplicationPackage { ...@@ -339,11 +339,11 @@ abstract class IOSApp extends ApplicationPackage {
return null; return null;
} }
if (!project.xcodeProject.existsSync()) { if (!project.xcodeProject.existsSync()) {
printError('Expected ios/Runner.xcodeproj but this file is missing.'); globals.printError('Expected ios/Runner.xcodeproj but this file is missing.');
return null; return null;
} }
if (!project.xcodeProjectInfoFile.existsSync()) { if (!project.xcodeProjectInfoFile.existsSync()) {
printError('Expected ios/Runner.xcodeproj/project.pbxproj but this file is missing.'); globals.printError('Expected ios/Runner.xcodeproj/project.pbxproj but this file is missing.');
return null; return null;
} }
return BuildableIOSApp.fromProject(project); return BuildableIOSApp.fromProject(project);
...@@ -378,7 +378,7 @@ class BuildableIOSApp extends IOSApp { ...@@ -378,7 +378,7 @@ class BuildableIOSApp extends IOSApp {
String get deviceBundlePath => _buildAppPath('iphoneos'); String get deviceBundlePath => _buildAppPath('iphoneos');
String _buildAppPath(String type) { String _buildAppPath(String type) {
return fs.path.join(getIosBuildDirectory(), type, name); return globals.fs.path.join(getIosBuildDirectory(), type, name);
} }
} }
...@@ -598,7 +598,7 @@ class ApkManifestData { ...@@ -598,7 +598,7 @@ class ApkManifestData {
final String packageName = package.value.substring(1, package.value.indexOf('" ')); final String packageName = package.value.substring(1, package.value.indexOf('" '));
if (launchActivity == null) { if (launchActivity == null) {
printError('Error running $packageName. Default activity not found'); globals.printError('Error running $packageName. Default activity not found');
return null; return null;
} }
...@@ -610,16 +610,16 @@ class ApkManifestData { ...@@ -610,16 +610,16 @@ class ApkManifestData {
// Example format: (type 0x10)0x1 // Example format: (type 0x10)0x1
final _Attribute versionCodeAttr = manifest.firstAttribute('android:versionCode'); final _Attribute versionCodeAttr = manifest.firstAttribute('android:versionCode');
if (versionCodeAttr == null) { if (versionCodeAttr == null) {
printError('Error running $packageName. Manifest versionCode not found'); globals.printError('Error running $packageName. Manifest versionCode not found');
return null; return null;
} }
if (!versionCodeAttr.value.startsWith('(type 0x10)')) { if (!versionCodeAttr.value.startsWith('(type 0x10)')) {
printError('Error running $packageName. Manifest versionCode invalid'); globals.printError('Error running $packageName. Manifest versionCode invalid');
return null; return null;
} }
final int versionCode = int.tryParse(versionCodeAttr.value.substring(11)); final int versionCode = int.tryParse(versionCodeAttr.value.substring(11));
if (versionCode == null) { if (versionCode == null) {
printError('Error running $packageName. Manifest versionCode invalid'); globals.printError('Error running $packageName. Manifest versionCode invalid');
return null; return null;
} }
......
This diff is collapsed.
...@@ -11,7 +11,7 @@ import '../build_info.dart'; ...@@ -11,7 +11,7 @@ import '../build_info.dart';
import '../bundle.dart'; import '../bundle.dart';
import '../compile.dart'; import '../compile.dart';
import '../dart/package_map.dart'; import '../dart/package_map.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import '../macos/xcode.dart'; import '../macos/xcode.dart';
import '../project.dart'; import '../project.dart';
import '../reporting/reporting.dart'; import '../reporting/reporting.dart';
...@@ -39,7 +39,7 @@ class GenSnapshot { ...@@ -39,7 +39,7 @@ class GenSnapshot {
const GenSnapshot(); const GenSnapshot();
static String getSnapshotterPath(SnapshotType snapshotType) { static String getSnapshotterPath(SnapshotType snapshotType) {
return artifacts.getArtifactPath( return globals.artifacts.getArtifactPath(
Artifact.genSnapshot, platform: snapshotType.platform, mode: snapshotType.mode); Artifact.genSnapshot, platform: snapshotType.platform, mode: snapshotType.mode);
} }
...@@ -97,12 +97,12 @@ class AOTSnapshotter { ...@@ -97,12 +97,12 @@ class AOTSnapshotter {
bool quiet = false, bool quiet = false,
}) async { }) async {
if (bitcode && platform != TargetPlatform.ios) { if (bitcode && platform != TargetPlatform.ios) {
printError('Bitcode is only supported for iOS.'); globals.printError('Bitcode is only supported for iOS.');
return 1; return 1;
} }
if (!_isValidAotPlatform(platform, buildMode)) { if (!_isValidAotPlatform(platform, buildMode)) {
printError('${getNameForTargetPlatform(platform)} does not support AOT compilation.'); globals.printError('${getNameForTargetPlatform(platform)} does not support AOT compilation.');
return 1; return 1;
} }
// TODO(cbracken): replace IOSArch with TargetPlatform.ios_{armv7,arm64}. // TODO(cbracken): replace IOSArch with TargetPlatform.ios_{armv7,arm64}.
...@@ -111,16 +111,16 @@ class AOTSnapshotter { ...@@ -111,16 +111,16 @@ class AOTSnapshotter {
final PackageMap packageMap = PackageMap(packagesPath); final PackageMap packageMap = PackageMap(packagesPath);
final String packageMapError = packageMap.checkValid(); final String packageMapError = packageMap.checkValid();
if (packageMapError != null) { if (packageMapError != null) {
printError(packageMapError); globals.printError(packageMapError);
return 1; return 1;
} }
final Directory outputDir = fs.directory(outputPath); final Directory outputDir = globals.fs.directory(outputPath);
outputDir.createSync(recursive: true); outputDir.createSync(recursive: true);
final String skyEnginePkg = _getPackagePath(packageMap, 'sky_engine'); final String skyEnginePkg = _getPackagePath(packageMap, 'sky_engine');
final String uiPath = fs.path.join(skyEnginePkg, 'lib', 'ui', 'ui.dart'); final String uiPath = globals.fs.path.join(skyEnginePkg, 'lib', 'ui', 'ui.dart');
final String vmServicePath = fs.path.join(skyEnginePkg, 'sdk_ext', 'vmservice_io.dart'); final String vmServicePath = globals.fs.path.join(skyEnginePkg, 'sdk_ext', 'vmservice_io.dart');
final List<String> inputPaths = <String>[uiPath, vmServicePath, mainPath]; final List<String> inputPaths = <String>[uiPath, vmServicePath, mainPath];
final Set<String> outputPaths = <String>{}; final Set<String> outputPaths = <String>{};
...@@ -128,18 +128,18 @@ class AOTSnapshotter { ...@@ -128,18 +128,18 @@ class AOTSnapshotter {
'--deterministic', '--deterministic',
]; ];
if (extraGenSnapshotOptions != null && extraGenSnapshotOptions.isNotEmpty) { if (extraGenSnapshotOptions != null && extraGenSnapshotOptions.isNotEmpty) {
printTrace('Extra gen_snapshot options: $extraGenSnapshotOptions'); globals.printTrace('Extra gen_snapshot options: $extraGenSnapshotOptions');
genSnapshotArgs.addAll(extraGenSnapshotOptions); genSnapshotArgs.addAll(extraGenSnapshotOptions);
} }
final String assembly = fs.path.join(outputDir.path, 'snapshot_assembly.S'); final String assembly = globals.fs.path.join(outputDir.path, 'snapshot_assembly.S');
if (platform == TargetPlatform.ios || platform == TargetPlatform.darwin_x64) { if (platform == TargetPlatform.ios || platform == TargetPlatform.darwin_x64) {
// Assembly AOT snapshot. // Assembly AOT snapshot.
outputPaths.add(assembly); outputPaths.add(assembly);
genSnapshotArgs.add('--snapshot_kind=app-aot-assembly'); genSnapshotArgs.add('--snapshot_kind=app-aot-assembly');
genSnapshotArgs.add('--assembly=$assembly'); genSnapshotArgs.add('--assembly=$assembly');
} else { } else {
final String aotSharedLibrary = fs.path.join(outputDir.path, 'app.so'); final String aotSharedLibrary = globals.fs.path.join(outputDir.path, 'app.so');
outputPaths.add(aotSharedLibrary); outputPaths.add(aotSharedLibrary);
genSnapshotArgs.add('--snapshot_kind=app-aot-elf'); genSnapshotArgs.add('--snapshot_kind=app-aot-elf');
genSnapshotArgs.add('--elf=$aotSharedLibrary'); genSnapshotArgs.add('--elf=$aotSharedLibrary');
...@@ -160,9 +160,9 @@ class AOTSnapshotter { ...@@ -160,9 +160,9 @@ class AOTSnapshotter {
// TODO(jonahwilliams): fully remove input checks once all callers are // TODO(jonahwilliams): fully remove input checks once all callers are
// using assemble. // using assemble.
final Iterable<String> missingInputs = inputPaths.where((String p) => !fs.isFileSync(p)); final Iterable<String> missingInputs = inputPaths.where((String p) => !globals.fs.isFileSync(p));
if (missingInputs.isNotEmpty) { if (missingInputs.isNotEmpty) {
printTrace('Missing input files: $missingInputs from $inputPaths'); globals.printTrace('Missing input files: $missingInputs from $inputPaths');
} }
final SnapshotType snapshotType = SnapshotType(platform, buildMode); final SnapshotType snapshotType = SnapshotType(platform, buildMode);
...@@ -174,7 +174,7 @@ class AOTSnapshotter { ...@@ -174,7 +174,7 @@ class AOTSnapshotter {
darwinArch: darwinArch, darwinArch: darwinArch,
)); ));
if (genSnapshotExitCode != 0) { if (genSnapshotExitCode != 0) {
printError('Dart snapshot generator failed with exit code $genSnapshotExitCode'); globals.printError('Dart snapshot generator failed with exit code $genSnapshotExitCode');
return genSnapshotExitCode; return genSnapshotExitCode;
} }
...@@ -184,8 +184,8 @@ class AOTSnapshotter { ...@@ -184,8 +184,8 @@ class AOTSnapshotter {
// gen_snapshot would provide an argument to do this automatically. // gen_snapshot would provide an argument to do this automatically.
final bool stripSymbols = platform == TargetPlatform.ios && buildMode == BuildMode.release && bitcode; final bool stripSymbols = platform == TargetPlatform.ios && buildMode == BuildMode.release && bitcode;
if (stripSymbols) { if (stripSymbols) {
final IOSink sink = fs.file('$assembly.stripped.S').openWrite(); final IOSink sink = globals.fs.file('$assembly.stripped.S').openWrite();
for (String line in fs.file(assembly).readAsLinesSync()) { for (String line in globals.fs.file(assembly).readAsLinesSync()) {
if (line.startsWith('.section __DWARF')) { if (line.startsWith('.section __DWARF')) {
break; break;
} }
...@@ -231,7 +231,7 @@ class AOTSnapshotter { ...@@ -231,7 +231,7 @@ class AOTSnapshotter {
}) async { }) async {
final String targetArch = getNameForDarwinArch(appleArch); final String targetArch = getNameForDarwinArch(appleArch);
if (!quiet) { if (!quiet) {
printStatus('Building App.framework for $targetArch...'); globals.printStatus('Building App.framework for $targetArch...');
} }
final List<String> commonBuildOptions = <String>[ final List<String> commonBuildOptions = <String>[
...@@ -241,7 +241,7 @@ class AOTSnapshotter { ...@@ -241,7 +241,7 @@ class AOTSnapshotter {
]; ];
const String embedBitcodeArg = '-fembed-bitcode'; const String embedBitcodeArg = '-fembed-bitcode';
final String assemblyO = fs.path.join(outputPath, 'snapshot_assembly.o'); final String assemblyO = globals.fs.path.join(outputPath, 'snapshot_assembly.o');
List<String> isysrootArgs; List<String> isysrootArgs;
if (isIOS) { if (isIOS) {
final String iPhoneSDKLocation = await xcode.sdkLocation(SdkType.iPhone); final String iPhoneSDKLocation = await xcode.sdkLocation(SdkType.iPhone);
...@@ -259,13 +259,13 @@ class AOTSnapshotter { ...@@ -259,13 +259,13 @@ class AOTSnapshotter {
assemblyO, assemblyO,
]); ]);
if (compileResult.exitCode != 0) { if (compileResult.exitCode != 0) {
printError('Failed to compile AOT snapshot. Compiler terminated with exit code ${compileResult.exitCode}'); globals.printError('Failed to compile AOT snapshot. Compiler terminated with exit code ${compileResult.exitCode}');
return compileResult; return compileResult;
} }
final String frameworkDir = fs.path.join(outputPath, 'App.framework'); final String frameworkDir = globals.fs.path.join(outputPath, 'App.framework');
fs.directory(frameworkDir).createSync(recursive: true); globals.fs.directory(frameworkDir).createSync(recursive: true);
final String appLib = fs.path.join(frameworkDir, 'App'); final String appLib = globals.fs.path.join(frameworkDir, 'App');
final List<String> linkArgs = <String>[ final List<String> linkArgs = <String>[
...commonBuildOptions, ...commonBuildOptions,
'-dynamiclib', '-dynamiclib',
...@@ -279,7 +279,7 @@ class AOTSnapshotter { ...@@ -279,7 +279,7 @@ class AOTSnapshotter {
]; ];
final RunResult linkResult = await xcode.clang(linkArgs); final RunResult linkResult = await xcode.clang(linkArgs);
if (linkResult.exitCode != 0) { if (linkResult.exitCode != 0) {
printError('Failed to link AOT snapshot. Linker terminated with exit code ${compileResult.exitCode}'); globals.printError('Failed to link AOT snapshot. Linker terminated with exit code ${compileResult.exitCode}');
} }
return linkResult; return linkResult;
} }
...@@ -298,25 +298,25 @@ class AOTSnapshotter { ...@@ -298,25 +298,25 @@ class AOTSnapshotter {
List<String> extraFrontEndOptions = const <String>[], List<String> extraFrontEndOptions = const <String>[],
}) async { }) async {
final FlutterProject flutterProject = FlutterProject.current(); final FlutterProject flutterProject = FlutterProject.current();
final Directory outputDir = fs.directory(outputPath); final Directory outputDir = globals.fs.directory(outputPath);
outputDir.createSync(recursive: true); outputDir.createSync(recursive: true);
printTrace('Compiling Dart to kernel: $mainPath'); globals.printTrace('Compiling Dart to kernel: $mainPath');
if ((extraFrontEndOptions != null) && extraFrontEndOptions.isNotEmpty) { if ((extraFrontEndOptions != null) && extraFrontEndOptions.isNotEmpty) {
printTrace('Extra front-end options: $extraFrontEndOptions'); globals.printTrace('Extra front-end options: $extraFrontEndOptions');
} }
final String depfilePath = fs.path.join(outputPath, 'kernel_compile.d'); final String depfilePath = globals.fs.path.join(outputPath, 'kernel_compile.d');
final KernelCompiler kernelCompiler = await kernelCompilerFactory.create(flutterProject); final KernelCompiler kernelCompiler = await kernelCompilerFactory.create(flutterProject);
final CompilerOutput compilerOutput = final CompilerOutput compilerOutput =
await _timedStep('frontend(CompileTime)', 'aot-kernel', await _timedStep('frontend(CompileTime)', 'aot-kernel',
() => kernelCompiler.compile( () => kernelCompiler.compile(
sdkRoot: artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath, mode: buildMode), sdkRoot: globals.artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath, mode: buildMode),
mainPath: mainPath, mainPath: mainPath,
packagesPath: packagesPath, packagesPath: packagesPath,
outputFilePath: getKernelPathForTransformerOptions( outputFilePath: getKernelPathForTransformerOptions(
fs.path.join(outputPath, 'app.dill'), globals.fs.path.join(outputPath, 'app.dill'),
trackWidgetCreation: trackWidgetCreation, trackWidgetCreation: trackWidgetCreation,
), ),
depFilePath: depfilePath, depFilePath: depfilePath,
...@@ -329,8 +329,8 @@ class AOTSnapshotter { ...@@ -329,8 +329,8 @@ class AOTSnapshotter {
)); ));
// Write path to frontend_server, since things need to be re-generated when that changes. // Write path to frontend_server, since things need to be re-generated when that changes.
final String frontendPath = artifacts.getArtifactPath(Artifact.frontendServerSnapshotForEngineDartSdk); final String frontendPath = globals.artifacts.getArtifactPath(Artifact.frontendServerSnapshotForEngineDartSdk);
fs.directory(outputPath).childFile('frontend_server.d').writeAsStringSync('frontend_server.d: $frontendPath\n'); globals.fs.directory(outputPath).childFile('frontend_server.d').writeAsStringSync('frontend_server.d: $frontendPath\n');
return compilerOutput?.outputFilename; return compilerOutput?.outputFilename;
} }
...@@ -349,7 +349,7 @@ class AOTSnapshotter { ...@@ -349,7 +349,7 @@ class AOTSnapshotter {
} }
String _getPackagePath(PackageMap packageMap, String package) { String _getPackagePath(PackageMap packageMap, String package) {
return fs.path.dirname(fs.path.fromUri(packageMap.map[package])); return globals.fs.path.dirname(globals.fs.path.fromUri(packageMap.map[package]));
} }
/// This method is used to measure duration of an action and emit it into /// This method is used to measure duration of an action and emit it into
...@@ -361,7 +361,7 @@ class AOTSnapshotter { ...@@ -361,7 +361,7 @@ class AOTSnapshotter {
final Stopwatch sw = Stopwatch()..start(); final Stopwatch sw = Stopwatch()..start();
final T value = await action(); final T value = await action();
if (reportTimings) { if (reportTimings) {
printStatus('$marker: ${sw.elapsedMilliseconds} ms.'); globals.printStatus('$marker: ${sw.elapsedMilliseconds} ms.');
} }
flutterUsage.sendTiming('build', analyticsVar, Duration(milliseconds: sw.elapsedMilliseconds)); flutterUsage.sendTiming('build', analyticsVar, Duration(milliseconds: sw.elapsedMilliseconds));
return value; return value;
......
...@@ -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 'file_system.dart'; import '../globals.dart' as globals;
import 'platform.dart';
/// Whether the tool started from the daemon, as opposed to the command line. /// Whether the tool started from the daemon, as opposed to the command line.
// TODO(jonahwilliams): remove once IDE updates have rolled. // TODO(jonahwilliams): remove once IDE updates have rolled.
...@@ -11,11 +10,11 @@ bool isRunningFromDaemon = false; ...@@ -11,11 +10,11 @@ bool isRunningFromDaemon = false;
/// Return the absolute path of the user's home directory /// Return the absolute path of the user's home directory
String get homeDirPath { String get homeDirPath {
String path = platform.isWindows String path = globals.platform.isWindows
? platform.environment['USERPROFILE'] ? globals.platform.environment['USERPROFILE']
: platform.environment['HOME']; : globals.platform.environment['HOME'];
if (path != null) { if (path != null) {
path = fs.path.absolute(path); path = globals.fs.path.absolute(path);
} }
return path; return path;
} }
......
...@@ -3,16 +3,15 @@ ...@@ -3,16 +3,15 @@
// found in the LICENSE file. // found in the LICENSE file.
import '../convert.dart'; import '../convert.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import 'context.dart';
import 'file_system.dart'; import 'file_system.dart';
import 'logger.dart'; import 'logger.dart';
import 'utils.dart'; import 'utils.dart';
class Config { class Config {
Config([File configFile, Logger localLogger]) { Config([File configFile, Logger localLogger]) {
final Logger loggerInstance = localLogger ?? logger; final Logger loggerInstance = localLogger ?? globals.logger;
_configFile = configFile ?? fs.file(fs.path.join(userHomePath(), '.flutter_settings')); _configFile = configFile ?? globals.fs.file(globals.fs.path.join(userHomePath(), '.flutter_settings'));
if (_configFile.existsSync()) { if (_configFile.existsSync()) {
try { try {
_values = castStringKeyedMap(json.decode(_configFile.readAsStringSync())); _values = castStringKeyedMap(json.decode(_configFile.readAsStringSync()));
...@@ -28,8 +27,6 @@ class Config { ...@@ -28,8 +27,6 @@ class Config {
} }
} }
static Config get instance => context.get<Config>();
File _configFile; File _configFile;
String get configPath => _configFile.path; String get configPath => _configFile.path;
......
...@@ -8,8 +8,8 @@ import 'dart:io' as io show Directory, File, Link; ...@@ -8,8 +8,8 @@ import 'dart:io' as io show Directory, File, Link;
import 'package:file/file.dart'; import 'package:file/file.dart';
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import '../globals.dart' as globals;
import 'common.dart' show throwToolExit; import 'common.dart' show throwToolExit;
import 'platform.dart';
// The Flutter tool hits file system errors that only the end-user can address. // The Flutter tool hits file system errors that only the end-user can address.
// We would like these errors to not hit crash logging. In these cases, we // We would like these errors to not hit crash logging. In these cases, we
...@@ -129,7 +129,7 @@ class ErrorHandlingFile ...@@ -129,7 +129,7 @@ class ErrorHandlingFile
try { try {
return await op(); return await op();
} on FileSystemException catch (e) { } on FileSystemException catch (e) {
if (platform.isWindows) { if (globals.platform.isWindows) {
_handleWindowsException(e, failureMessage); _handleWindowsException(e, failureMessage);
} }
rethrow; rethrow;
...@@ -140,7 +140,7 @@ class ErrorHandlingFile ...@@ -140,7 +140,7 @@ class ErrorHandlingFile
try { try {
return op(); return op();
} on FileSystemException catch (e) { } on FileSystemException catch (e) {
if (platform.isWindows) { if (globals.platform.isWindows) {
_handleWindowsException(e, failureMessage); _handleWindowsException(e, failureMessage);
} }
rethrow; rethrow;
......
...@@ -3,36 +3,22 @@ ...@@ -3,36 +3,22 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'package:file/file.dart'; import 'package:file/file.dart';
import 'package:file/local.dart';
import 'package:file/memory.dart';
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import '../globals.dart' as globals;
import 'common.dart' show throwToolExit; import 'common.dart' show throwToolExit;
import 'context.dart';
import 'error_handling_file_system.dart';
import 'platform.dart';
export 'package:file/file.dart'; export 'package:file/file.dart';
export 'package:file/local.dart'; export 'package:file/local.dart';
const FileSystem _kLocalFs = LocalFileSystem();
/// Currently active implementation of the file system.
///
/// By default it uses local disk-based implementation. Override this in tests
/// with [MemoryFileSystem].
FileSystem get fs => ErrorHandlingFileSystem(
context.get<FileSystem>() ?? _kLocalFs,
);
/// 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) {
final String dirPath = fs.path.dirname(filePath); final String dirPath = globals.fs.path.dirname(filePath);
if (fs.isDirectorySync(dirPath)) { if (globals.fs.isDirectorySync(dirPath)) {
return; return;
} }
try { try {
fs.directory(dirPath).createSync(recursive: true); globals.fs.directory(dirPath).createSync(recursive: true);
} on FileSystemException catch (e) { } on FileSystemException catch (e) {
throwToolExit('Failed to create directory "$dirPath": ${e.osError.message}'); throwToolExit('Failed to create directory "$dirPath": ${e.osError.message}');
} }
...@@ -84,13 +70,13 @@ void copyDirectorySync( ...@@ -84,13 +70,13 @@ void copyDirectorySync(
/// `package:path`. However, unlike the original, it does not change the ASCII /// `package:path`. However, unlike the original, it does not change the ASCII
/// case of the path. Changing the case can break hot reload in some situations, /// case of the path. Changing the case can break hot reload in some situations,
/// for an example see: https://github.com/flutter/flutter/issues/9539. /// for an example see: https://github.com/flutter/flutter/issues/9539.
String canonicalizePath(String path) => fs.path.normalize(fs.path.absolute(path)); String canonicalizePath(String path) => globals.fs.path.normalize(globals.fs.path.absolute(path));
/// Escapes [path]. /// Escapes [path].
/// ///
/// On Windows it replaces all '\' with '\\'. On other platforms, it returns the /// On Windows it replaces all '\' with '\\'. On other platforms, it returns the
/// path unchanged. /// path unchanged.
String escapePath(String path) => platform.isWindows ? path.replaceAll('\\', '\\\\') : path; String escapePath(String path) => globals.platform.isWindows ? path.replaceAll('\\', '\\\\') : path;
/// Returns true if the file system [entity] has not been modified since the /// Returns true if the file system [entity] has not been modified since the
/// latest modification to [referenceFile]. /// latest modification to [referenceFile].
...@@ -120,6 +106,6 @@ class FileNotFoundException implements IOException { ...@@ -120,6 +106,6 @@ class FileNotFoundException implements IOException {
/// ///
/// If the searched environment variables are not set, '.' is returned instead. /// If the searched environment variables are not set, '.' is returned instead.
String userHomePath() { String userHomePath() {
final String envKey = platform.operatingSystem == 'windows' ? 'APPDATA' : 'HOME'; final String envKey = globals.platform.operatingSystem == 'windows' ? 'APPDATA' : 'HOME';
return platform.environment[envKey] ?? '.'; return globals.platform.environment[envKey] ?? '.';
} }
...@@ -7,7 +7,7 @@ import 'package:meta/meta.dart'; ...@@ -7,7 +7,7 @@ import 'package:meta/meta.dart';
import 'package:quiver/core.dart' show hash2; import 'package:quiver/core.dart' show hash2;
import '../convert.dart' show json; import '../convert.dart' show json;
import '../globals.dart'; import '../globals.dart' as globals;
import '../version.dart'; import '../version.dart';
import 'file_system.dart'; import 'file_system.dart';
import 'utils.dart'; import 'utils.dart';
...@@ -50,17 +50,17 @@ class Fingerprinter { ...@@ -50,17 +50,17 @@ class Fingerprinter {
bool doesFingerprintMatch() { bool doesFingerprintMatch() {
try { try {
final File fingerprintFile = fs.file(fingerprintPath); final File fingerprintFile = globals.fs.file(fingerprintPath);
if (!fingerprintFile.existsSync()) { if (!fingerprintFile.existsSync()) {
return false; return false;
} }
if (!_depfilePaths.every(fs.isFileSync)) { if (!_depfilePaths.every(globals.fs.isFileSync)) {
return false; return false;
} }
final List<String> paths = _getPaths(); final List<String> paths = _getPaths();
if (!paths.every(fs.isFileSync)) { if (!paths.every(globals.fs.isFileSync)) {
return false; return false;
} }
...@@ -69,7 +69,7 @@ class Fingerprinter { ...@@ -69,7 +69,7 @@ class Fingerprinter {
return oldFingerprint == newFingerprint; return oldFingerprint == newFingerprint;
} catch (e) { } catch (e) {
// Log exception and continue, fingerprinting is only a performance improvement. // Log exception and continue, fingerprinting is only a performance improvement.
printTrace('Fingerprint check error: $e'); globals.printTrace('Fingerprint check error: $e');
} }
return false; return false;
} }
...@@ -77,10 +77,10 @@ class Fingerprinter { ...@@ -77,10 +77,10 @@ class Fingerprinter {
void writeFingerprint() { void writeFingerprint() {
try { try {
final Fingerprint fingerprint = buildFingerprint(); final Fingerprint fingerprint = buildFingerprint();
fs.file(fingerprintPath).writeAsStringSync(fingerprint.toJson()); globals.fs.file(fingerprintPath).writeAsStringSync(fingerprint.toJson());
} catch (e) { } catch (e) {
// Log exception and continue, fingerprinting is only a performance improvement. // Log exception and continue, fingerprinting is only a performance improvement.
printTrace('Fingerprint write error: $e'); globals.printTrace('Fingerprint write error: $e');
} }
} }
...@@ -101,7 +101,7 @@ class Fingerprinter { ...@@ -101,7 +101,7 @@ class Fingerprinter {
/// See [Fingerprinter]. /// See [Fingerprinter].
class Fingerprint { class Fingerprint {
Fingerprint.fromBuildInputs(Map<String, String> properties, Iterable<String> inputPaths) { Fingerprint.fromBuildInputs(Map<String, String> properties, Iterable<String> inputPaths) {
final Iterable<File> files = inputPaths.map<File>(fs.file); final Iterable<File> files = inputPaths.map<File>(globals.fs.file);
final Iterable<File> missingInputs = files.where((File file) => !file.existsSync()); final Iterable<File> missingInputs = files.where((File file) => !file.existsSync());
if (missingInputs.isNotEmpty) { if (missingInputs.isNotEmpty) {
throw ArgumentError('Missing input files:\n' + missingInputs.join('\n')); throw ArgumentError('Missing input files:\n' + missingInputs.join('\n'));
...@@ -181,7 +181,7 @@ final RegExp _escapeExpr = RegExp(r'\\(.)'); ...@@ -181,7 +181,7 @@ final RegExp _escapeExpr = RegExp(r'\\(.)');
Set<String> readDepfile(String depfilePath) { Set<String> readDepfile(String depfilePath) {
// Depfile format: // Depfile format:
// outfile1 outfile2 : file1.dart file2.dart file3.dart // outfile1 outfile2 : file1.dart file2.dart file3.dart
final String contents = fs.file(depfilePath).readAsStringSync(); final String contents = globals.fs.file(depfilePath).readAsStringSync();
final String dependencies = contents.split(': ')[1]; final String dependencies = contents.split(': ')[1];
return dependencies return dependencies
......
...@@ -45,8 +45,8 @@ import 'dart:io' as io ...@@ -45,8 +45,8 @@ import 'dart:io' as io
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import '../globals.dart' as globals;
import 'context.dart'; import 'context.dart';
import 'platform.dart';
import 'process.dart'; import 'process.dart';
export 'dart:io' export 'dart:io'
...@@ -180,7 +180,7 @@ class ProcessSignal { ...@@ -180,7 +180,7 @@ class ProcessSignal {
/// ///
/// This is implemented by sending the signal using [Process.killPid]. /// This is implemented by sending the signal using [Process.killPid].
bool send(int pid) { bool send(int pid) {
assert(!platform.isWindows || this == ProcessSignal.SIGTERM); assert(!globals.platform.isWindows || this == ProcessSignal.SIGTERM);
return io.Process.killPid(pid, _delegate); return io.Process.killPid(pid, _delegate);
} }
...@@ -197,7 +197,7 @@ class _PosixProcessSignal extends ProcessSignal { ...@@ -197,7 +197,7 @@ class _PosixProcessSignal extends ProcessSignal {
@override @override
Stream<ProcessSignal> watch() { Stream<ProcessSignal> watch() {
if (platform.isWindows) { if (globals.platform.isWindows) {
return const Stream<ProcessSignal>.empty(); return const Stream<ProcessSignal>.empty();
} }
return super.watch(); return super.watch();
......
...@@ -7,8 +7,8 @@ import 'dart:async'; ...@@ -7,8 +7,8 @@ import 'dart:async';
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import '../base/context.dart'; import '../base/context.dart';
import '../globals.dart' as globals;
import 'io.dart'; import 'io.dart';
import 'platform.dart';
import 'terminal.dart'; import 'terminal.dart';
import 'utils.dart'; import 'utils.dart';
...@@ -44,7 +44,7 @@ abstract class Logger { ...@@ -44,7 +44,7 @@ abstract class Logger {
bool quiet = false; bool quiet = false;
bool get supportsColor => terminal.supportsColor; bool get supportsColor => globals.terminal.supportsColor;
bool get hasTerminal => stdio.hasTerminal; bool get hasTerminal => stdio.hasTerminal;
...@@ -174,9 +174,9 @@ class StdoutLogger extends Logger { ...@@ -174,9 +174,9 @@ class StdoutLogger extends Logger {
message ??= ''; message ??= '';
message = wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap); message = wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap);
if (emphasis == true) { if (emphasis == true) {
message = terminal.bolden(message); message = globals.terminal.bolden(message);
} }
message = terminal.color(message, color ?? TerminalColor.red); message = globals.terminal.color(message, color ?? TerminalColor.red);
stderr.writeln(message); stderr.writeln(message);
if (stackTrace != null) { if (stackTrace != null) {
stderr.writeln(stackTrace.toString()); stderr.writeln(stackTrace.toString());
...@@ -198,10 +198,10 @@ class StdoutLogger extends Logger { ...@@ -198,10 +198,10 @@ class StdoutLogger extends Logger {
message ??= ''; message ??= '';
message = wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap); message = wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap);
if (emphasis == true) { if (emphasis == true) {
message = terminal.bolden(message); message = globals.terminal.bolden(message);
} }
if (color != null) { if (color != null) {
message = terminal.color(message, color); message = globals.terminal.color(message, color);
} }
if (newline != false) { if (newline != false) {
message = '$message\n'; message = '$message\n';
...@@ -234,7 +234,7 @@ class StdoutLogger extends Logger { ...@@ -234,7 +234,7 @@ class StdoutLogger extends Logger {
onFinish: _clearStatus, onFinish: _clearStatus,
)..start(); )..start();
} }
if (terminal.supportsColor) { if (globals.terminal.supportsColor) {
_status = AnsiStatus( _status = AnsiStatus(
message: message, message: message,
timeout: timeout, timeout: timeout,
...@@ -305,7 +305,7 @@ class BufferLogger extends Logger { ...@@ -305,7 +305,7 @@ class BufferLogger extends Logger {
int hangingIndent, int hangingIndent,
bool wrap, bool wrap,
}) { }) {
_error.writeln(terminal.color( _error.writeln(globals.terminal.color(
wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap), wrapText(message, indent: indent, hangingIndent: hangingIndent, shouldWrap: wrap),
color ?? TerminalColor.red, color ?? TerminalColor.red,
)); ));
...@@ -356,7 +356,7 @@ class BufferLogger extends Logger { ...@@ -356,7 +356,7 @@ class BufferLogger extends Logger {
} }
class VerboseLogger extends Logger { class VerboseLogger extends Logger {
VerboseLogger(this.parent) : assert(terminal != null) { VerboseLogger(this.parent) : assert(globals.terminal != null) {
_stopwatch.start(); _stopwatch.start();
} }
...@@ -446,7 +446,7 @@ class VerboseLogger extends Logger { ...@@ -446,7 +446,7 @@ class VerboseLogger extends Logger {
} else { } else {
prefix = '+$millis ms'.padLeft(prefixWidth); prefix = '+$millis ms'.padLeft(prefixWidth);
if (millis >= 100) { if (millis >= 100) {
prefix = terminal.bolden(prefix); prefix = globals.terminal.bolden(prefix);
} }
} }
prefix = '[$prefix] '; prefix = '[$prefix] ';
...@@ -455,12 +455,12 @@ class VerboseLogger extends Logger { ...@@ -455,12 +455,12 @@ class VerboseLogger extends Logger {
final String indentMessage = message.replaceAll('\n', '\n$indent'); final String indentMessage = message.replaceAll('\n', '\n$indent');
if (type == _LogType.error) { if (type == _LogType.error) {
parent.printError(prefix + terminal.bolden(indentMessage)); parent.printError(prefix + globals.terminal.bolden(indentMessage));
if (stackTrace != null) { if (stackTrace != null) {
parent.printError(indent + stackTrace.toString().replaceAll('\n', '\n$indent')); parent.printError(indent + stackTrace.toString().replaceAll('\n', '\n$indent'));
} }
} else if (type == _LogType.status) { } else if (type == _LogType.status) {
parent.printStatus(prefix + terminal.bolden(indentMessage)); parent.printStatus(prefix + globals.terminal.bolden(indentMessage));
} else { } else {
parent.printStatus(prefix + indentMessage); parent.printStatus(prefix + indentMessage);
} }
...@@ -504,7 +504,7 @@ abstract class Status { ...@@ -504,7 +504,7 @@ abstract class Status {
VoidCallback onFinish, VoidCallback onFinish,
SlowWarningCallback slowWarningCallback, SlowWarningCallback slowWarningCallback,
}) { }) {
if (terminal.supportsColor) { if (globals.terminal.supportsColor) {
return AnsiSpinner( return AnsiSpinner(
timeout: timeout, timeout: timeout,
onFinish: onFinish, onFinish: onFinish,
...@@ -663,7 +663,7 @@ class AnsiSpinner extends Status { ...@@ -663,7 +663,7 @@ class AnsiSpinner extends Status {
Timer timer; Timer timer;
// Windows console font has a limited set of Unicode characters. // Windows console font has a limited set of Unicode characters.
List<String> get _animation => platform.isWindows List<String> get _animation => globals.platform.isWindows
? <String>[r'-', r'\', r'|', r'/'] ? <String>[r'-', r'\', r'|', r'/']
: <String>['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷']; : <String>['⣾', '⣽', '⣻', '⢿', '⡿', '⣟', '⣯', '⣷'];
......
...@@ -6,11 +6,10 @@ import 'dart:async'; ...@@ -6,11 +6,10 @@ import 'dart:async';
import '../base/context.dart'; import '../base/context.dart';
import '../convert.dart'; import '../convert.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import 'common.dart'; import 'common.dart';
import 'file_system.dart'; import 'file_system.dart';
import 'io.dart'; import 'io.dart';
import 'platform.dart';
const int kNetworkProblemExitCode = 50; const int kNetworkProblemExitCode = 50;
...@@ -52,10 +51,10 @@ Future<List<int>> fetchUrl(Uri url, { ...@@ -52,10 +51,10 @@ Future<List<int>> fetchUrl(Uri url, {
} }
if (maxAttempts != null && attempts >= maxAttempts) { if (maxAttempts != null && attempts >= maxAttempts) {
printStatus('Download failed -- retry $attempts'); globals.printStatus('Download failed -- retry $attempts');
return null; return null;
} }
printStatus('Download failed -- attempting retry $attempts in ' globals.printStatus('Download failed -- attempting retry $attempts in '
'$durationSeconds second${ durationSeconds == 1 ? "" : "s"}...'); '$durationSeconds second${ durationSeconds == 1 ? "" : "s"}...');
await Future<void>.delayed(Duration(seconds: durationSeconds)); await Future<void>.delayed(Duration(seconds: durationSeconds));
if (durationSeconds < 64) { if (durationSeconds < 64) {
...@@ -73,7 +72,7 @@ Future<bool> _attempt(Uri url, { ...@@ -73,7 +72,7 @@ Future<bool> _attempt(Uri url, {
bool onlyHeaders = false, bool onlyHeaders = false,
}) async { }) async {
assert(onlyHeaders || destSink != null); assert(onlyHeaders || destSink != null);
printTrace('Downloading: $url'); globals.printTrace('Downloading: $url');
HttpClient httpClient; HttpClient httpClient;
if (context.get<HttpClientFactory>() != null) { if (context.get<HttpClientFactory>() != null) {
httpClient = context.get<HttpClientFactory>()(); httpClient = context.get<HttpClientFactory>()();
...@@ -90,9 +89,9 @@ Future<bool> _attempt(Uri url, { ...@@ -90,9 +89,9 @@ Future<bool> _attempt(Uri url, {
} }
response = await request.close(); response = await request.close();
} on ArgumentError catch (error) { } on ArgumentError catch (error) {
final String overrideUrl = platform.environment['FLUTTER_STORAGE_BASE_URL']; final String overrideUrl = globals.platform.environment['FLUTTER_STORAGE_BASE_URL'];
if (overrideUrl != null && url.toString().contains(overrideUrl)) { if (overrideUrl != null && url.toString().contains(overrideUrl)) {
printError(error.toString()); globals.printError(error.toString());
throwToolExit( throwToolExit(
'The value of FLUTTER_STORAGE_BASE_URL ($overrideUrl) could not be ' 'The value of FLUTTER_STORAGE_BASE_URL ($overrideUrl) could not be '
'parsed as a valid url. Please see https://flutter.dev/community/china ' 'parsed as a valid url. Please see https://flutter.dev/community/china '
...@@ -100,10 +99,10 @@ Future<bool> _attempt(Uri url, { ...@@ -100,10 +99,10 @@ Future<bool> _attempt(Uri url, {
'Full URL: $url', 'Full URL: $url',
exitCode: kNetworkProblemExitCode,); exitCode: kNetworkProblemExitCode,);
} }
printError(error.toString()); globals.printError(error.toString());
rethrow; rethrow;
} on HandshakeException catch (error) { } on HandshakeException catch (error) {
printTrace(error.toString()); globals.printTrace(error.toString());
throwToolExit( throwToolExit(
'Could not authenticate download server. You may be experiencing a man-in-the-middle attack,\n' 'Could not authenticate download server. You may be experiencing a man-in-the-middle attack,\n'
'your network may be compromised, or you may have malware installed on your computer.\n' 'your network may be compromised, or you may have malware installed on your computer.\n'
...@@ -111,10 +110,10 @@ Future<bool> _attempt(Uri url, { ...@@ -111,10 +110,10 @@ Future<bool> _attempt(Uri url, {
exitCode: kNetworkProblemExitCode, exitCode: kNetworkProblemExitCode,
); );
} on SocketException catch (error) { } on SocketException catch (error) {
printTrace('Download error: $error'); globals.printTrace('Download error: $error');
return false; return false;
} on HttpException catch (error) { } on HttpException catch (error) {
printTrace('Download error: $error'); globals.printTrace('Download error: $error');
return false; return false;
} }
assert(response != null); assert(response != null);
...@@ -134,16 +133,16 @@ Future<bool> _attempt(Uri url, { ...@@ -134,16 +133,16 @@ Future<bool> _attempt(Uri url, {
); );
} }
// 5xx errors are server errors and we can try again // 5xx errors are server errors and we can try again
printTrace('Download error: ${response.statusCode} ${response.reasonPhrase}'); globals.printTrace('Download error: ${response.statusCode} ${response.reasonPhrase}');
return false; return false;
} }
printTrace('Received response from server, collecting bytes...'); globals.printTrace('Received response from server, collecting bytes...');
try { try {
assert(destSink != null); assert(destSink != null);
await response.forEach(destSink.add); await response.forEach(destSink.add);
return true; return true;
} on IOException catch (error) { } on IOException catch (error) {
printTrace('Download error: $error'); globals.printTrace('Download error: $error');
return false; return false;
} finally { } finally {
await destSink?.flush(); await destSink?.flush();
......
...@@ -4,20 +4,18 @@ ...@@ -4,20 +4,18 @@
import 'package:archive/archive.dart'; import 'package:archive/archive.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import 'context.dart'; import 'context.dart';
import 'file_system.dart'; import 'file_system.dart';
import 'io.dart'; import 'io.dart';
import 'platform.dart';
import 'process.dart'; import 'process.dart';
import 'process_manager.dart';
/// Returns [OperatingSystemUtils] active in the current app context (i.e. zone). /// Returns [OperatingSystemUtils] active in the current app context (i.e. zone).
OperatingSystemUtils get os => context.get<OperatingSystemUtils>(); OperatingSystemUtils get os => context.get<OperatingSystemUtils>();
abstract class OperatingSystemUtils { abstract class OperatingSystemUtils {
factory OperatingSystemUtils() { factory OperatingSystemUtils() {
if (platform.isWindows) { if (globals.platform.isWindows) {
return _WindowsUtils(); return _WindowsUtils();
} else { } else {
return _PosixUtils(); return _PosixUtils();
...@@ -75,7 +73,7 @@ abstract class OperatingSystemUtils { ...@@ -75,7 +73,7 @@ abstract class OperatingSystemUtils {
'linux': 'Linux', 'linux': 'Linux',
'windows': 'Windows', 'windows': 'Windows',
}; };
final String osName = platform.operatingSystem; final String osName = globals.platform.operatingSystem;
return osNames.containsKey(osName) ? osNames[osName] : osName; return osNames.containsKey(osName) ? osNames[osName] : osName;
} }
...@@ -103,10 +101,10 @@ abstract class OperatingSystemUtils { ...@@ -103,10 +101,10 @@ abstract class OperatingSystemUtils {
if (!ipv6) { if (!ipv6) {
return findFreePort(ipv6: true); return findFreePort(ipv6: true);
} }
printTrace('findFreePort failed: $e'); globals.printTrace('findFreePort failed: $e');
} catch (e) { } catch (e) {
// Failures are signaled by a return value of 0 from this function. // Failures are signaled by a return value of 0 from this function.
printTrace('findFreePort failed: $e'); globals.printTrace('findFreePort failed: $e');
} finally { } finally {
if (serverSocket != null) { if (serverSocket != null) {
await serverSocket.close(); await serverSocket.close();
...@@ -127,16 +125,16 @@ class _PosixUtils extends OperatingSystemUtils { ...@@ -127,16 +125,16 @@ class _PosixUtils extends OperatingSystemUtils {
@override @override
void chmod(FileSystemEntity entity, String mode) { void chmod(FileSystemEntity entity, String mode) {
try { try {
final ProcessResult result = processManager.runSync(<String>['chmod', mode, entity.path]); final ProcessResult result = globals.processManager.runSync(<String>['chmod', mode, entity.path]);
if (result.exitCode != 0) { if (result.exitCode != 0) {
printTrace( globals.printTrace(
'Error trying to run chmod on ${entity.absolute.path}' 'Error trying to run chmod on ${entity.absolute.path}'
'\nstdout: ${result.stdout}' '\nstdout: ${result.stdout}'
'\nstderr: ${result.stderr}', '\nstderr: ${result.stderr}',
); );
} }
} on ProcessException catch (error) { } on ProcessException catch (error) {
printTrace('Error trying to run chmod on ${entity.absolute.path}: $error'); globals.printTrace('Error trying to run chmod on ${entity.absolute.path}: $error');
} }
} }
...@@ -147,12 +145,12 @@ class _PosixUtils extends OperatingSystemUtils { ...@@ -147,12 +145,12 @@ class _PosixUtils extends OperatingSystemUtils {
if (all) '-a', if (all) '-a',
execName, execName,
]; ];
final ProcessResult result = processManager.runSync(command); final ProcessResult result = globals.processManager.runSync(command);
if (result.exitCode != 0) { if (result.exitCode != 0) {
return const <File>[]; return const <File>[];
} }
final String stdout = result.stdout as String; final String stdout = result.stdout as String;
return stdout.trim().split('\n').map<File>((String path) => fs.file(path.trim())).toList(); return stdout.trim().split('\n').map<File>((String path) => globals.fs.file(path.trim())).toList();
} }
@override @override
...@@ -196,7 +194,7 @@ class _PosixUtils extends OperatingSystemUtils { ...@@ -196,7 +194,7 @@ class _PosixUtils extends OperatingSystemUtils {
<String>['mkfifo', path], <String>['mkfifo', path],
throwOnError: true, throwOnError: true,
); );
return fs.file(path); return globals.fs.file(path);
} }
String _name; String _name;
...@@ -204,7 +202,7 @@ class _PosixUtils extends OperatingSystemUtils { ...@@ -204,7 +202,7 @@ class _PosixUtils extends OperatingSystemUtils {
@override @override
String get name { String get name {
if (_name == null) { if (_name == null) {
if (platform.isMacOS) { if (globals.platform.isMacOS) {
final List<RunResult> results = <RunResult>[ final List<RunResult> results = <RunResult>[
processUtils.runSync(<String>['sw_vers', '-productName']), processUtils.runSync(<String>['sw_vers', '-productName']),
processUtils.runSync(<String>['sw_vers', '-productVersion']), processUtils.runSync(<String>['sw_vers', '-productVersion']),
...@@ -236,15 +234,15 @@ class _WindowsUtils extends OperatingSystemUtils { ...@@ -236,15 +234,15 @@ class _WindowsUtils extends OperatingSystemUtils {
@override @override
List<File> _which(String execName, { bool all = false }) { List<File> _which(String execName, { bool all = false }) {
// `where` always returns all matches, not just the first one. // `where` always returns all matches, not just the first one.
final ProcessResult result = processManager.runSync(<String>['where', execName]); final ProcessResult result = globals.processManager.runSync(<String>['where', execName]);
if (result.exitCode != 0) { if (result.exitCode != 0) {
return const <File>[]; return const <File>[];
} }
final List<String> lines = (result.stdout as String).trim().split('\n'); final List<String> lines = (result.stdout as String).trim().split('\n');
if (all) { if (all) {
return lines.map<File>((String path) => fs.file(path.trim())).toList(); return lines.map<File>((String path) => globals.fs.file(path.trim())).toList();
} }
return <File>[fs.file(lines.first.trim())]; return <File>[globals.fs.file(lines.first.trim())];
} }
@override @override
...@@ -307,7 +305,7 @@ class _WindowsUtils extends OperatingSystemUtils { ...@@ -307,7 +305,7 @@ class _WindowsUtils extends OperatingSystemUtils {
continue; continue;
} }
final File destFile = fs.file(fs.path.join(targetDirectory.path, archiveFile.name)); final File destFile = globals.fs.file(globals.fs.path.join(targetDirectory.path, archiveFile.name));
if (!destFile.parent.existsSync()) { if (!destFile.parent.existsSync()) {
destFile.parent.createSync(recursive: true); destFile.parent.createSync(recursive: true);
} }
...@@ -325,7 +323,7 @@ class _WindowsUtils extends OperatingSystemUtils { ...@@ -325,7 +323,7 @@ class _WindowsUtils extends OperatingSystemUtils {
@override @override
String get name { String get name {
if (_name == null) { if (_name == null) {
final ProcessResult result = processManager.runSync( final ProcessResult result = globals.processManager.runSync(
<String>['ver'], runInShell: true); <String>['ver'], runInShell: true);
if (result.exitCode == 0) { if (result.exitCode == 0) {
_name = (result.stdout as String).trim(); _name = (result.stdout as String).trim();
...@@ -346,12 +344,12 @@ class _WindowsUtils extends OperatingSystemUtils { ...@@ -346,12 +344,12 @@ class _WindowsUtils extends OperatingSystemUtils {
/// 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 ??= fs.currentDirectory.path; directory ??= globals.fs.currentDirectory.path;
while (true) { while (true) {
if (fs.isFileSync(fs.path.join(directory, kProjectRootSentinel))) { if (globals.fs.isFileSync(globals.fs.path.join(directory, kProjectRootSentinel))) {
return directory; return directory;
} }
final String parent = fs.path.dirname(directory); final String parent = globals.fs.path.dirname(directory);
if (directory == parent) { if (directory == parent) {
return null; return null;
} }
......
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:platform/platform.dart';
import 'context.dart';
export 'package:platform/platform.dart';
const Platform _kLocalPlatform = LocalPlatform();
Platform get platform => context.get<Platform>() ?? _kLocalPlatform;
...@@ -5,12 +5,10 @@ ...@@ -5,12 +5,10 @@
import 'dart:async'; import 'dart:async';
import '../convert.dart'; import '../convert.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import 'common.dart'; import 'common.dart';
import 'context.dart'; import 'context.dart';
import 'file_system.dart';
import 'io.dart'; import 'io.dart';
import 'process_manager.dart';
import 'utils.dart'; import 'utils.dart';
typedef StringConverter = String Function(String string); typedef StringConverter = String Function(String string);
...@@ -77,11 +75,11 @@ void addShutdownHook( ...@@ -77,11 +75,11 @@ void addShutdownHook(
/// guaranteed to run to completion before shutdown hooks in the next stage are /// guaranteed to run to completion before shutdown hooks in the next stage are
/// started. /// started.
Future<void> runShutdownHooks() async { Future<void> runShutdownHooks() async {
printTrace('Running shutdown hooks'); globals.printTrace('Running shutdown hooks');
_shutdownHooksRunning = true; _shutdownHooksRunning = true;
try { try {
for (ShutdownStage stage in _shutdownHooks.keys.toList()..sort()) { for (ShutdownStage stage in _shutdownHooks.keys.toList()..sort()) {
printTrace('Shutdown hook priority ${stage.priority}'); globals.printTrace('Shutdown hook priority ${stage.priority}');
final List<ShutdownHook> hooks = _shutdownHooks.remove(stage); final List<ShutdownHook> hooks = _shutdownHooks.remove(stage);
final List<Future<dynamic>> futures = <Future<dynamic>>[]; final List<Future<dynamic>> futures = <Future<dynamic>>[];
for (ShutdownHook shutdownHook in hooks) { for (ShutdownHook shutdownHook in hooks) {
...@@ -96,7 +94,7 @@ Future<void> runShutdownHooks() async { ...@@ -96,7 +94,7 @@ Future<void> runShutdownHooks() async {
_shutdownHooksRunning = false; _shutdownHooksRunning = false;
} }
assert(_shutdownHooks.isEmpty); assert(_shutdownHooks.isEmpty);
printTrace('Shutdown hooks complete'); globals.printTrace('Shutdown hooks complete');
} }
class ProcessExit implements Exception { class ProcessExit implements Exception {
...@@ -261,15 +259,15 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -261,15 +259,15 @@ class _DefaultProcessUtils implements ProcessUtils {
_traceCommand(cmd, workingDirectory: workingDirectory); _traceCommand(cmd, workingDirectory: workingDirectory);
// When there is no timeout, there's no need to kill a running process, so // When there is no timeout, there's no need to kill a running process, so
// we can just use processManager.run(). // we can just use globals.processManager.run().
if (timeout == null) { if (timeout == null) {
final ProcessResult results = await processManager.run( final ProcessResult results = await globals.processManager.run(
cmd, cmd,
workingDirectory: workingDirectory, workingDirectory: workingDirectory,
environment: _environment(allowReentrantFlutter, environment), environment: _environment(allowReentrantFlutter, environment),
); );
final RunResult runResult = RunResult(results, cmd); final RunResult runResult = RunResult(results, cmd);
printTrace(runResult.toString()); globals.printTrace(runResult.toString());
if (throwOnError && runResult.exitCode != 0 && if (throwOnError && runResult.exitCode != 0 &&
(whiteListFailures == null || !whiteListFailures(runResult.exitCode))) { (whiteListFailures == null || !whiteListFailures(runResult.exitCode))) {
runResult.throwException('Process exited abnormally:\n$runResult'); runResult.throwException('Process exited abnormally:\n$runResult');
...@@ -278,7 +276,7 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -278,7 +276,7 @@ class _DefaultProcessUtils implements ProcessUtils {
} }
// When there is a timeout, we have to kill the running process, so we have // When there is a timeout, we have to kill the running process, so we have
// to use processManager.start() through _runCommand() above. // to use globals.processManager.start() through _runCommand() above.
while (true) { while (true) {
assert(timeoutRetries >= 0); assert(timeoutRetries >= 0);
timeoutRetries = timeoutRetries - 1; timeoutRetries = timeoutRetries - 1;
...@@ -304,7 +302,7 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -304,7 +302,7 @@ class _DefaultProcessUtils implements ProcessUtils {
int exitCode; int exitCode;
exitCode = await process.exitCode.timeout(timeout, onTimeout: () { exitCode = await process.exitCode.timeout(timeout, onTimeout: () {
// The process timed out. Kill it. // The process timed out. Kill it.
processManager.killPid(process.pid); globals.processManager.killPid(process.pid);
return null; return null;
}); });
...@@ -333,7 +331,7 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -333,7 +331,7 @@ class _DefaultProcessUtils implements ProcessUtils {
// If the process did not timeout. We are done. // If the process did not timeout. We are done.
if (exitCode != null) { if (exitCode != null) {
printTrace(runResult.toString()); globals.printTrace(runResult.toString());
if (throwOnError && runResult.exitCode != 0 && if (throwOnError && runResult.exitCode != 0 &&
(whiteListFailures == null || !whiteListFailures(exitCode))) { (whiteListFailures == null || !whiteListFailures(exitCode))) {
runResult.throwException('Process exited abnormally:\n$runResult'); runResult.throwException('Process exited abnormally:\n$runResult');
...@@ -347,7 +345,7 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -347,7 +345,7 @@ class _DefaultProcessUtils implements ProcessUtils {
} }
// Log the timeout with a trace message in verbose mode. // Log the timeout with a trace message in verbose mode.
printTrace('Process "${cmd[0]}" timed out. $timeoutRetries attempts left:\n' globals.printTrace('Process "${cmd[0]}" timed out. $timeoutRetries attempts left:\n'
'$runResult'); '$runResult');
} }
...@@ -365,14 +363,14 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -365,14 +363,14 @@ class _DefaultProcessUtils implements ProcessUtils {
bool allowReentrantFlutter = false, bool allowReentrantFlutter = false,
}) { }) {
_traceCommand(cmd, workingDirectory: workingDirectory); _traceCommand(cmd, workingDirectory: workingDirectory);
final ProcessResult results = processManager.runSync( final ProcessResult results = globals.processManager.runSync(
cmd, cmd,
workingDirectory: workingDirectory, workingDirectory: workingDirectory,
environment: _environment(allowReentrantFlutter, environment), environment: _environment(allowReentrantFlutter, environment),
); );
final RunResult runResult = RunResult(results, cmd); final RunResult runResult = RunResult(results, cmd);
printTrace('Exit code ${runResult.exitCode} from: ${cmd.join(' ')}'); globals.printTrace('Exit code ${runResult.exitCode} from: ${cmd.join(' ')}');
bool failedExitCode = runResult.exitCode != 0; bool failedExitCode = runResult.exitCode != 0;
if (whiteListFailures != null && failedExitCode) { if (whiteListFailures != null && failedExitCode) {
...@@ -381,17 +379,17 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -381,17 +379,17 @@ class _DefaultProcessUtils implements ProcessUtils {
if (runResult.stdout.isNotEmpty && !hideStdout) { if (runResult.stdout.isNotEmpty && !hideStdout) {
if (failedExitCode && throwOnError) { if (failedExitCode && throwOnError) {
printStatus(runResult.stdout.trim()); globals.printStatus(runResult.stdout.trim());
} else { } else {
printTrace(runResult.stdout.trim()); globals.printTrace(runResult.stdout.trim());
} }
} }
if (runResult.stderr.isNotEmpty) { if (runResult.stderr.isNotEmpty) {
if (failedExitCode && throwOnError) { if (failedExitCode && throwOnError) {
printError(runResult.stderr.trim()); globals.printError(runResult.stderr.trim());
} else { } else {
printTrace(runResult.stderr.trim()); globals.printTrace(runResult.stderr.trim());
} }
} }
...@@ -410,7 +408,7 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -410,7 +408,7 @@ class _DefaultProcessUtils implements ProcessUtils {
Map<String, String> environment, Map<String, String> environment,
}) { }) {
_traceCommand(cmd, workingDirectory: workingDirectory); _traceCommand(cmd, workingDirectory: workingDirectory);
return processManager.start( return globals.processManager.start(
cmd, cmd,
workingDirectory: workingDirectory, workingDirectory: workingDirectory,
environment: _environment(allowReentrantFlutter, environment), environment: _environment(allowReentrantFlutter, environment),
...@@ -445,9 +443,9 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -445,9 +443,9 @@ class _DefaultProcessUtils implements ProcessUtils {
if (line != null) { if (line != null) {
final String message = '$prefix$line'; final String message = '$prefix$line';
if (trace) { if (trace) {
printTrace(message); globals.printTrace(message);
} else { } else {
printStatus(message, wrap: false); globals.printStatus(message, wrap: false);
} }
} }
}); });
...@@ -460,7 +458,7 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -460,7 +458,7 @@ class _DefaultProcessUtils implements ProcessUtils {
line = mapFunction(line); line = mapFunction(line);
} }
if (line != null) { if (line != null) {
printError('$prefix$line', wrap: false); globals.printError('$prefix$line', wrap: false);
} }
}); });
...@@ -489,9 +487,9 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -489,9 +487,9 @@ class _DefaultProcessUtils implements ProcessUtils {
}) { }) {
_traceCommand(cli); _traceCommand(cli);
try { try {
return processManager.runSync(cli, environment: environment).exitCode == 0; return globals.processManager.runSync(cli, environment: environment).exitCode == 0;
} catch (error) { } catch (error) {
printTrace('$cli failed with $error'); globals.printTrace('$cli failed with $error');
return false; return false;
} }
} }
...@@ -503,9 +501,9 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -503,9 +501,9 @@ class _DefaultProcessUtils implements ProcessUtils {
}) async { }) async {
_traceCommand(cli); _traceCommand(cli);
try { try {
return (await processManager.run(cli, environment: environment)).exitCode == 0; return (await globals.processManager.run(cli, environment: environment)).exitCode == 0;
} catch (error) { } catch (error) {
printTrace('$cli failed with $error'); globals.printTrace('$cli failed with $error');
return false; return false;
} }
} }
...@@ -527,9 +525,9 @@ class _DefaultProcessUtils implements ProcessUtils { ...@@ -527,9 +525,9 @@ class _DefaultProcessUtils implements ProcessUtils {
void _traceCommand(List<String> args, { String workingDirectory }) { void _traceCommand(List<String> args, { String workingDirectory }) {
final String argsText = args.join(' '); final String argsText = args.join(' ');
if (workingDirectory == null) { if (workingDirectory == null) {
printTrace('executing: $argsText'); globals.printTrace('executing: $argsText');
} else { } else {
printTrace('executing: [$workingDirectory${fs.path.separator}] $argsText'); globals.printTrace('executing: [$workingDirectory${globals.fs.path.separator}] $argsText');
} }
} }
} }
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:process/process.dart';
import 'context.dart';
const ProcessManager _kLocalProcessManager = LocalProcessManager();
/// The active process manager.
ProcessManager get processManager => context.get<ProcessManager>() ?? _kLocalProcessManager;
...@@ -5,10 +5,9 @@ ...@@ -5,10 +5,9 @@
import 'dart:async'; import 'dart:async';
import '../convert.dart'; import '../convert.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import 'context.dart'; import 'context.dart';
import 'io.dart' as io; import 'io.dart' as io;
import 'platform.dart';
enum TerminalColor { enum TerminalColor {
red, red,
...@@ -20,22 +19,16 @@ enum TerminalColor { ...@@ -20,22 +19,16 @@ enum TerminalColor {
grey, grey,
} }
AnsiTerminal get terminal {
return context?.get<AnsiTerminal>() ?? _defaultAnsiTerminal;
}
/// Warning mark to use in stdout or stderr. /// Warning mark to use in stdout or stderr.
String get warningMark { String get warningMark {
return terminal.bolden(terminal.color('[!]', TerminalColor.red)); return globals.terminal.bolden(globals.terminal.color('[!]', TerminalColor.red));
} }
/// Success mark to use in stdout. /// Success mark to use in stdout.
String get successMark { String get successMark {
return terminal.bolden(terminal.color('✓', TerminalColor.green)); return globals.terminal.bolden(globals.terminal.color('✓', TerminalColor.green));
} }
final AnsiTerminal _defaultAnsiTerminal = AnsiTerminal();
OutputPreferences get outputPreferences { OutputPreferences get outputPreferences {
return context?.get<OutputPreferences>() ?? _defaultOutputPreferences; return context?.get<OutputPreferences>() ?? _defaultOutputPreferences;
} }
...@@ -50,7 +43,7 @@ class OutputPreferences { ...@@ -50,7 +43,7 @@ class OutputPreferences {
bool showColor, bool showColor,
}) : wrapText = wrapText ?? io.stdio.hasTerminal, }) : wrapText = wrapText ?? io.stdio.hasTerminal,
_overrideWrapColumn = wrapColumn, _overrideWrapColumn = wrapColumn,
showColor = showColor ?? platform.stdoutSupportsAnsi ?? false; showColor = showColor ?? globals.platform.stdoutSupportsAnsi ?? false;
/// A version of this class for use in tests. /// A version of this class for use in tests.
OutputPreferences.test() : wrapText = false, _overrideWrapColumn = null, showColor = false; OutputPreferences.test() : wrapText = false, _overrideWrapColumn = null, showColor = false;
...@@ -114,7 +107,7 @@ class AnsiTerminal { ...@@ -114,7 +107,7 @@ class AnsiTerminal {
static String colorCode(TerminalColor color) => _colorMap[color]; static String colorCode(TerminalColor color) => _colorMap[color];
bool get supportsColor => platform.stdoutSupportsAnsi ?? false; bool get supportsColor => globals.platform.stdoutSupportsAnsi ?? false;
final RegExp _boldControls = RegExp('(${RegExp.escape(resetBold)}|${RegExp.escape(bold)})'); final RegExp _boldControls = RegExp('(${RegExp.escape(resetBold)}|${RegExp.escape(bold)})');
/// Whether we are interacting with the flutter tool via the terminal. /// Whether we are interacting with the flutter tool via the terminal.
...@@ -227,14 +220,14 @@ class AnsiTerminal { ...@@ -227,14 +220,14 @@ class AnsiTerminal {
singleCharMode = true; singleCharMode = true;
while (choice == null || choice.length > 1 || !acceptedCharacters.contains(choice)) { while (choice == null || choice.length > 1 || !acceptedCharacters.contains(choice)) {
if (prompt != null) { if (prompt != null) {
printStatus(prompt, emphasis: true, newline: false); globals.printStatus(prompt, emphasis: true, newline: false);
if (displayAcceptedCharacters) { if (displayAcceptedCharacters) {
printStatus(' [${charactersToDisplay.join("|")}]', newline: false); globals.printStatus(' [${charactersToDisplay.join("|")}]', newline: false);
} }
printStatus(': ', emphasis: true, newline: false); globals.printStatus(': ', emphasis: true, newline: false);
} }
choice = await keystrokes.first; choice = await keystrokes.first;
printStatus(choice); globals.printStatus(choice);
} }
singleCharMode = false; singleCharMode = false;
if (defaultChoiceIndex != null && choice == '\n') { if (defaultChoiceIndex != null && choice == '\n') {
......
...@@ -8,10 +8,10 @@ import 'dart:math' show Random, max; ...@@ -8,10 +8,10 @@ import 'dart:math' show Random, max;
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import '../convert.dart'; import '../convert.dart';
import '../globals.dart' as globals;
import 'context.dart'; import 'context.dart';
import 'file_system.dart'; import 'file_system.dart';
import 'io.dart' as io; import 'io.dart' as io;
import 'platform.dart';
import 'terminal.dart'; import 'terminal.dart';
const BotDetector _kBotDetector = BotDetector(); const BotDetector _kBotDetector = BotDetector();
...@@ -22,40 +22,40 @@ class BotDetector { ...@@ -22,40 +22,40 @@ class BotDetector {
bool get isRunningOnBot { bool get isRunningOnBot {
if ( if (
// Explicitly stated to not be a bot. // Explicitly stated to not be a bot.
platform.environment['BOT'] == 'false' globals.platform.environment['BOT'] == 'false'
// Set by the IDEs to the IDE name, so a strong signal that this is not a bot. // Set by the IDEs to the IDE name, so a strong signal that this is not a bot.
|| platform.environment.containsKey('FLUTTER_HOST') || globals.platform.environment.containsKey('FLUTTER_HOST')
// When set, GA logs to a local file (normally for tests) so we don't need to filter. // When set, GA logs to a local file (normally for tests) so we don't need to filter.
|| platform.environment.containsKey('FLUTTER_ANALYTICS_LOG_FILE') || globals.platform.environment.containsKey('FLUTTER_ANALYTICS_LOG_FILE')
) { ) {
return false; return false;
} }
return platform.environment['BOT'] == 'true' return globals.platform.environment['BOT'] == 'true'
// https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables // https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables
|| platform.environment['TRAVIS'] == 'true' || globals.platform.environment['TRAVIS'] == 'true'
|| platform.environment['CONTINUOUS_INTEGRATION'] == 'true' || globals.platform.environment['CONTINUOUS_INTEGRATION'] == 'true'
|| platform.environment.containsKey('CI') // Travis and AppVeyor || globals.platform.environment.containsKey('CI') // Travis and AppVeyor
// https://www.appveyor.com/docs/environment-variables/ // https://www.appveyor.com/docs/environment-variables/
|| platform.environment.containsKey('APPVEYOR') || globals.platform.environment.containsKey('APPVEYOR')
// https://cirrus-ci.org/guide/writing-tasks/#environment-variables // https://cirrus-ci.org/guide/writing-tasks/#environment-variables
|| platform.environment.containsKey('CIRRUS_CI') || globals.platform.environment.containsKey('CIRRUS_CI')
// https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html // https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html
|| (platform.environment.containsKey('AWS_REGION') && || (globals.platform.environment.containsKey('AWS_REGION') &&
platform.environment.containsKey('CODEBUILD_INITIATOR')) globals.platform.environment.containsKey('CODEBUILD_INITIATOR'))
// https://wiki.jenkins.io/display/JENKINS/Building+a+software+project#Buildingasoftwareproject-belowJenkinsSetEnvironmentVariables // https://wiki.jenkins.io/display/JENKINS/Building+a+software+project#Buildingasoftwareproject-belowJenkinsSetEnvironmentVariables
|| platform.environment.containsKey('JENKINS_URL') || globals.platform.environment.containsKey('JENKINS_URL')
// Properties on Flutter's Chrome Infra bots. // Properties on Flutter's Chrome Infra bots.
|| platform.environment['CHROME_HEADLESS'] == '1' || globals.platform.environment['CHROME_HEADLESS'] == '1'
|| platform.environment.containsKey('BUILDBOT_BUILDERNAME') || globals.platform.environment.containsKey('BUILDBOT_BUILDERNAME')
|| platform.environment.containsKey('SWARMING_TASK_ID'); || globals.platform.environment.containsKey('SWARMING_TASK_ID');
} }
} }
...@@ -107,7 +107,7 @@ File getUniqueFile(Directory dir, String baseName, String ext) { ...@@ -107,7 +107,7 @@ File getUniqueFile(Directory dir, String baseName, String ext) {
while (true) { while (true) {
final String name = '${baseName}_${i.toString().padLeft(2, '0')}.$ext'; final String name = '${baseName}_${i.toString().padLeft(2, '0')}.$ext';
final File file = fs.file(fs.path.join(dir.path, name)); final File file = fs.file(globals.fs.path.join(dir.path, name));
if (!file.existsSync()) { if (!file.existsSync()) {
return file; return file;
} }
...@@ -139,7 +139,7 @@ String getElapsedAsMilliseconds(Duration duration) { ...@@ -139,7 +139,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) {
final String cwd = fs.currentDirectory.path + fs.path.separator; final String cwd = globals.fs.currentDirectory.path + globals.fs.path.separator;
return fullPath.startsWith(cwd) ? fullPath.substring(cwd.length) : fullPath; return fullPath.startsWith(cwd) ? fullPath.substring(cwd.length) : fullPath;
} }
...@@ -368,7 +368,7 @@ String wrapText(String text, { int columnWidth, int hangingIndent, int indent, b ...@@ -368,7 +368,7 @@ String wrapText(String text, { int columnWidth, int hangingIndent, int indent, b
void writePidFile(String pidFile) { void writePidFile(String pidFile) {
if (pidFile != null) { if (pidFile != null) {
// Write our pid to the file. // Write our pid to the file.
fs.file(pidFile).writeAsStringSync(io.pid.toString()); globals.fs.file(pidFile).writeAsStringSync(io.pid.toString());
} }
} }
......
...@@ -3,10 +3,8 @@ ...@@ -3,10 +3,8 @@
// found in the LICENSE file. // found in the LICENSE file.
import 'base/context.dart'; import 'base/context.dart';
import 'base/file_system.dart';
import 'base/platform.dart';
import 'base/utils.dart'; import 'base/utils.dart';
import 'globals.dart'; import 'globals.dart' as globals;
/// Information about a build to be performed or used. /// Information about a build to be performed or used.
class BuildInfo { class BuildInfo {
...@@ -221,7 +219,7 @@ String validatedBuildNumberForPlatform(TargetPlatform targetPlatform, String bui ...@@ -221,7 +219,7 @@ String validatedBuildNumberForPlatform(TargetPlatform targetPlatform, String bui
} }
tmpBuildNumber = segments.join('.'); tmpBuildNumber = segments.join('.');
if (tmpBuildNumber != buildNumber) { if (tmpBuildNumber != buildNumber) {
printTrace('Invalid build-number: $buildNumber for iOS/macOS, overridden by $tmpBuildNumber.\n' globals.printTrace('Invalid build-number: $buildNumber for iOS/macOS, overridden by $tmpBuildNumber.\n'
'See CFBundleVersion at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html'); 'See CFBundleVersion at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html');
} }
return tmpBuildNumber; return tmpBuildNumber;
...@@ -239,7 +237,7 @@ String validatedBuildNumberForPlatform(TargetPlatform targetPlatform, String bui ...@@ -239,7 +237,7 @@ String validatedBuildNumberForPlatform(TargetPlatform targetPlatform, String bui
} }
tmpBuildNumberStr = tmpBuildNumberInt.toString(); tmpBuildNumberStr = tmpBuildNumberInt.toString();
if (tmpBuildNumberStr != buildNumber) { if (tmpBuildNumberStr != buildNumber) {
printTrace('Invalid build-number: $buildNumber for Android, overridden by $tmpBuildNumberStr.\n' globals.printTrace('Invalid build-number: $buildNumber for Android, overridden by $tmpBuildNumberStr.\n'
'See versionCode at https://developer.android.com/studio/publish/versioning'); 'See versionCode at https://developer.android.com/studio/publish/versioning');
} }
return tmpBuildNumberStr; return tmpBuildNumberStr;
...@@ -268,7 +266,7 @@ String validatedBuildNameForPlatform(TargetPlatform targetPlatform, String build ...@@ -268,7 +266,7 @@ String validatedBuildNameForPlatform(TargetPlatform targetPlatform, String build
} }
tmpBuildName = segments.join('.'); tmpBuildName = segments.join('.');
if (tmpBuildName != buildName) { if (tmpBuildName != buildName) {
printTrace('Invalid build-name: $buildName for iOS/macOS, overridden by $tmpBuildName.\n' globals.printTrace('Invalid build-name: $buildName for iOS/macOS, overridden by $tmpBuildName.\n'
'See CFBundleShortVersionString at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html'); 'See CFBundleShortVersionString at https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html');
} }
return tmpBuildName; return tmpBuildName;
...@@ -507,17 +505,17 @@ String fuchsiaArchForTargetPlatform(TargetPlatform targetPlatform) { ...@@ -507,17 +505,17 @@ String fuchsiaArchForTargetPlatform(TargetPlatform targetPlatform) {
} }
HostPlatform getCurrentHostPlatform() { HostPlatform getCurrentHostPlatform() {
if (platform.isMacOS) { if (globals.platform.isMacOS) {
return HostPlatform.darwin_x64; return HostPlatform.darwin_x64;
} }
if (platform.isLinux) { if (globals.platform.isLinux) {
return HostPlatform.linux_x64; return HostPlatform.linux_x64;
} }
if (platform.isWindows) { if (globals.platform.isWindows) {
return HostPlatform.windows_x64; return HostPlatform.windows_x64;
} }
printError('Unsupported host platform, defaulting to Linux'); globals.printError('Unsupported host platform, defaulting to Linux');
return HostPlatform.linux_x64; return HostPlatform.linux_x64;
} }
...@@ -526,14 +524,14 @@ HostPlatform getCurrentHostPlatform() { ...@@ -526,14 +524,14 @@ HostPlatform getCurrentHostPlatform() {
String getBuildDirectory() { String getBuildDirectory() {
// TODO(johnmccutchan): Stop calling this function as part of setting // TODO(johnmccutchan): Stop calling this function as part of setting
// up command line argument processing. // up command line argument processing.
if (context == null || config == null) { if (context == null || globals.config == null) {
return 'build'; return 'build';
} }
final String buildDir = config.getValue('build-dir') as String ?? 'build'; final String buildDir = globals.config.getValue('build-dir') as String ?? 'build';
if (fs.path.isAbsolute(buildDir)) { if (globals.fs.path.isAbsolute(buildDir)) {
throw Exception( throw Exception(
'build-dir config setting in ${config.configPath} must be relative'); 'build-dir config setting in ${globals.config.configPath} must be relative');
} }
return buildDir; return buildDir;
} }
...@@ -546,40 +544,40 @@ String getAndroidBuildDirectory() { ...@@ -546,40 +544,40 @@ String getAndroidBuildDirectory() {
/// Returns the AOT build output directory. /// Returns the AOT build output directory.
String getAotBuildDirectory() { String getAotBuildDirectory() {
return fs.path.join(getBuildDirectory(), 'aot'); return globals.fs.path.join(getBuildDirectory(), 'aot');
} }
/// Returns the asset build output directory. /// Returns the asset build output directory.
String getAssetBuildDirectory() { String getAssetBuildDirectory() {
return fs.path.join(getBuildDirectory(), 'flutter_assets'); return globals.fs.path.join(getBuildDirectory(), 'flutter_assets');
} }
/// Returns the iOS build output directory. /// Returns the iOS build output directory.
String getIosBuildDirectory() { String getIosBuildDirectory() {
return fs.path.join(getBuildDirectory(), 'ios'); return globals.fs.path.join(getBuildDirectory(), 'ios');
} }
/// Returns the macOS build output directory. /// Returns the macOS build output directory.
String getMacOSBuildDirectory() { String getMacOSBuildDirectory() {
return fs.path.join(getBuildDirectory(), 'macos'); return globals.fs.path.join(getBuildDirectory(), 'macos');
} }
/// Returns the web build output directory. /// Returns the web build output directory.
String getWebBuildDirectory() { String getWebBuildDirectory() {
return fs.path.join(getBuildDirectory(), 'web'); return globals.fs.path.join(getBuildDirectory(), 'web');
} }
/// Returns the Linux build output directory. /// Returns the Linux build output directory.
String getLinuxBuildDirectory() { String getLinuxBuildDirectory() {
return fs.path.join(getBuildDirectory(), 'linux'); return globals.fs.path.join(getBuildDirectory(), 'linux');
} }
/// Returns the Windows build output directory. /// Returns the Windows build output directory.
String getWindowsBuildDirectory() { String getWindowsBuildDirectory() {
return fs.path.join(getBuildDirectory(), 'windows'); return globals.fs.path.join(getBuildDirectory(), 'windows');
} }
/// Returns the Fuchsia build output directory. /// Returns the Fuchsia build output directory.
String getFuchsiaBuildDirectory() { String getFuchsiaBuildDirectory() {
return fs.path.join(getBuildDirectory(), 'fuchsia'); return globals.fs.path.join(getBuildDirectory(), 'fuchsia');
} }
...@@ -17,12 +17,10 @@ import '../base/common.dart'; ...@@ -17,12 +17,10 @@ import '../base/common.dart';
import '../base/file_system.dart'; import '../base/file_system.dart';
import '../base/io.dart'; import '../base/io.dart';
import '../base/logger.dart'; import '../base/logger.dart';
import '../base/platform.dart';
import '../base/process_manager.dart';
import '../codegen.dart'; import '../codegen.dart';
import '../dart/pub.dart'; import '../dart/pub.dart';
import '../dart/sdk.dart'; import '../dart/sdk.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import '../project.dart'; import '../project.dart';
/// The minimum version of build_runner we can support in the flutter tool. /// The minimum version of build_runner we can support in the flutter tool.
...@@ -39,8 +37,8 @@ class BuildRunner extends CodeGenerator { ...@@ -39,8 +37,8 @@ class BuildRunner extends CodeGenerator {
@override @override
Future<void> generateBuildScript(FlutterProject flutterProject) async { Future<void> generateBuildScript(FlutterProject flutterProject) async {
final Directory entrypointDirectory = fs.directory(fs.path.join(flutterProject.dartTool.path, 'build', 'entrypoint')); final Directory entrypointDirectory = globals.fs.directory(globals.fs.path.join(flutterProject.dartTool.path, 'build', 'entrypoint'));
final Directory generatedDirectory = fs.directory(fs.path.join(flutterProject.dartTool.path, 'flutter_tool')); final Directory generatedDirectory = globals.fs.directory(globals.fs.path.join(flutterProject.dartTool.path, 'flutter_tool'));
final File buildSnapshot = entrypointDirectory.childFile('build.dart.snapshot'); final File buildSnapshot = entrypointDirectory.childFile('build.dart.snapshot');
final File scriptIdFile = entrypointDirectory.childFile('id'); final File scriptIdFile = entrypointDirectory.childFile('id');
final File syntheticPubspec = generatedDirectory.childFile('pubspec.yaml'); final File syntheticPubspec = generatedDirectory.childFile('pubspec.yaml');
...@@ -69,7 +67,7 @@ class BuildRunner extends CodeGenerator { ...@@ -69,7 +67,7 @@ class BuildRunner extends CodeGenerator {
if (flutterProject.dartTool.existsSync()) { if (flutterProject.dartTool.existsSync()) {
flutterProject.dartTool.deleteSync(recursive: true); flutterProject.dartTool.deleteSync(recursive: true);
} }
final Status status = logger.startProgress('generating build script...', timeout: null); final Status status = globals.logger.startProgress('generating build script...', timeout: null);
try { try {
generatedDirectory.createSync(recursive: true); generatedDirectory.createSync(recursive: true);
entrypointDirectory.createSync(recursive: true); entrypointDirectory.createSync(recursive: true);
...@@ -86,8 +84,8 @@ class BuildRunner extends CodeGenerator { ...@@ -86,8 +84,8 @@ class BuildRunner extends CodeGenerator {
// parent directories. // parent directories.
if (node is YamlMap && node['path'] != null) { if (node is YamlMap && node['path'] != null) {
final String path = node['path'] as String; final String path = node['path'] as String;
if (fs.path.isRelative(path)) { if (globals.fs.path.isRelative(path)) {
final String convertedPath = fs.path.join('..', '..', path); final String convertedPath = globals.fs.path.join('..', '..', path);
stringBuffer.writeln(' $name:'); stringBuffer.writeln(' $name:');
stringBuffer.writeln(' path: $convertedPath'); stringBuffer.writeln(' path: $convertedPath');
} else { } else {
...@@ -112,18 +110,18 @@ class BuildRunner extends CodeGenerator { ...@@ -112,18 +110,18 @@ class BuildRunner extends CodeGenerator {
scriptIdFile.createSync(recursive: true); scriptIdFile.createSync(recursive: true);
} }
scriptIdFile.writeAsBytesSync(appliedBuilderDigest); scriptIdFile.writeAsBytesSync(appliedBuilderDigest);
final ProcessResult generateResult = await processManager.run(<String>[ final ProcessResult generateResult = await globals.processManager.run(<String>[
sdkBinaryName('pub'), 'run', 'build_runner', 'generate-build-script', sdkBinaryName('pub'), 'run', 'build_runner', 'generate-build-script',
], workingDirectory: syntheticPubspec.parent.path); ], workingDirectory: syntheticPubspec.parent.path);
if (generateResult.exitCode != 0) { if (generateResult.exitCode != 0) {
throwToolExit('Error generating build_script snapshot: ${generateResult.stderr}'); throwToolExit('Error generating build_script snapshot: ${generateResult.stderr}');
} }
final File buildScript = fs.file(generateResult.stdout.trim()); final File buildScript = globals.fs.file(generateResult.stdout.trim());
final ProcessResult result = await processManager.run(<String>[ final ProcessResult result = await globals.processManager.run(<String>[
artifacts.getArtifactPath(Artifact.engineDartBinary), globals.artifacts.getArtifactPath(Artifact.engineDartBinary),
'--snapshot=${buildSnapshot.path}', '--snapshot=${buildSnapshot.path}',
'--snapshot-kind=app-jit', '--snapshot-kind=app-jit',
'--packages=${fs.path.join(generatedDirectory.path, '.packages')}', '--packages=${globals.fs.path.join(generatedDirectory.path, '.packages')}',
buildScript.path, buildScript.path,
]); ]);
if (result.exitCode != 0) { if (result.exitCode != 0) {
...@@ -143,7 +141,7 @@ class BuildRunner extends CodeGenerator { ...@@ -143,7 +141,7 @@ class BuildRunner extends CodeGenerator {
List<String> extraFrontEndOptions = const <String> [], List<String> extraFrontEndOptions = const <String> [],
}) async { }) async {
await generateBuildScript(flutterProject); await generateBuildScript(flutterProject);
final String engineDartBinaryPath = artifacts.getArtifactPath(Artifact.engineDartBinary); final String engineDartBinaryPath = globals.artifacts.getArtifactPath(Artifact.engineDartBinary);
final File buildSnapshot = flutterProject final File buildSnapshot = flutterProject
.dartTool .dartTool
.childDirectory('build') .childDirectory('build')
...@@ -154,7 +152,7 @@ class BuildRunner extends CodeGenerator { ...@@ -154,7 +152,7 @@ class BuildRunner extends CodeGenerator {
.childDirectory('flutter_tool') .childDirectory('flutter_tool')
.childFile('.packages') .childFile('.packages')
.path; .path;
final Status status = logger.startProgress('starting build daemon...', timeout: null); final Status status = globals.logger.startProgress('starting build daemon...', timeout: null);
BuildDaemonClient buildDaemonClient; BuildDaemonClient buildDaemonClient;
try { try {
final List<String> command = <String>[ final List<String> command = <String>[
...@@ -170,7 +168,7 @@ class BuildRunner extends CodeGenerator { ...@@ -170,7 +168,7 @@ class BuildRunner extends CodeGenerator {
command, command,
logHandler: (ServerLog log) { logHandler: (ServerLog log) {
if (log.message != null) { if (log.message != null) {
printTrace(log.message); globals.printTrace(log.message);
} }
}, },
); );
...@@ -228,7 +226,7 @@ class _BuildRunnerCodegenDaemon implements CodegenDaemon { ...@@ -228,7 +226,7 @@ class _BuildRunnerCodegenDaemon implements CodegenDaemon {
// Sorts the builders by name and produces a hashcode of the resulting iterable. // Sorts the builders by name and produces a hashcode of the resulting iterable.
List<int> _produceScriptId(YamlMap builders) { List<int> _produceScriptId(YamlMap builders) {
if (builders == null || builders.isEmpty) { if (builders == null || builders.isEmpty) {
return md5.convert(platform.version.codeUnits).bytes; return md5.convert(globals.platform.version.codeUnits).bytes;
} }
final List<String> orderedBuilderNames = builders.keys final List<String> orderedBuilderNames = builders.keys
.cast<String>() .cast<String>()
...@@ -239,6 +237,6 @@ List<int> _produceScriptId(YamlMap builders) { ...@@ -239,6 +237,6 @@ List<int> _produceScriptId(YamlMap builders) {
return md5.convert(<String>[ return md5.convert(<String>[
...orderedBuilderNames, ...orderedBuilderNames,
...orderedBuilderValues, ...orderedBuilderValues,
platform.version, globals.platform.version,
].join('').codeUnits).bytes; ].join('').codeUnits).bytes;
} }
...@@ -16,6 +16,7 @@ import 'package:path/path.dart' as path; ...@@ -16,6 +16,7 @@ import 'package:path/path.dart' as path;
import '../base/file_system.dart'; import '../base/file_system.dart';
import '../build_info.dart'; import '../build_info.dart';
import '../convert.dart'; import '../convert.dart';
import '../globals.dart' as globals;
import '../platform_plugins.dart'; import '../platform_plugins.dart';
import '../plugins.dart'; import '../plugins.dart';
import '../project.dart'; import '../project.dart';
...@@ -81,14 +82,14 @@ class BuildRunnerWebCompilationProxy extends WebCompilationProxy { ...@@ -81,14 +82,14 @@ class BuildRunnerWebCompilationProxy extends WebCompilationProxy {
.listSync() .listSync()
.whereType<Directory>(); .whereType<Directory>();
for (Directory childDirectory in childDirectories) { for (Directory childDirectory in childDirectories) {
final String path = fs.path.join(testOutputDir, 'packages', final String path = globals.fs.path.join(testOutputDir, 'packages',
fs.path.basename(childDirectory.path)); globals.fs.path.basename(childDirectory.path));
copyDirectorySync(childDirectory.childDirectory('lib'), fs.directory(path)); copyDirectorySync(childDirectory.childDirectory('lib'), globals.fs.directory(path));
} }
final Directory outputDirectory = rootDirectory final Directory outputDirectory = rootDirectory
.childDirectory(projectName) .childDirectory(projectName)
.childDirectory('test'); .childDirectory('test');
copyDirectorySync(outputDirectory, fs.directory(fs.path.join(testOutputDir))); copyDirectorySync(outputDirectory, globals.fs.directory(globals.fs.path.join(testOutputDir)));
} }
return success; return success;
} }
...@@ -133,18 +134,18 @@ class MultirootFileBasedAssetReader extends core.FileBasedAssetReader { ...@@ -133,18 +134,18 @@ class MultirootFileBasedAssetReader extends core.FileBasedAssetReader {
@override @override
Stream<AssetId> findAssets(Glob glob, {String package}) async* { Stream<AssetId> findAssets(Glob glob, {String package}) async* {
if (package == null || packageGraph.root.name == package) { if (package == null || packageGraph.root.name == package) {
final String generatedRoot = fs.path.join(generatedDirectory.path, packageGraph.root.name); final String generatedRoot = globals.fs.path.join(generatedDirectory.path, packageGraph.root.name);
await for (io.FileSystemEntity entity in glob.list(followLinks: true, root: packageGraph.root.path)) { await for (io.FileSystemEntity entity in glob.list(followLinks: true, root: packageGraph.root.path)) {
if (entity is io.File && _isNotHidden(entity) && !fs.path.isWithin(generatedRoot, entity.path)) { if (entity is io.File && _isNotHidden(entity) && !globals.fs.path.isWithin(generatedRoot, entity.path)) {
yield _fileToAssetId(entity, packageGraph.root); yield _fileToAssetId(entity, packageGraph.root);
} }
} }
if (!fs.isDirectorySync(generatedRoot)) { if (!globals.fs.isDirectorySync(generatedRoot)) {
return; return;
} }
await for (io.FileSystemEntity entity in glob.list(followLinks: true, root: generatedRoot)) { await for (io.FileSystemEntity entity in glob.list(followLinks: true, root: generatedRoot)) {
if (entity is io.File && _isNotHidden(entity)) { if (entity is io.File && _isNotHidden(entity)) {
yield _fileToAssetId(entity, packageGraph.root, fs.path.relative(generatedRoot), true); yield _fileToAssetId(entity, packageGraph.root, globals.fs.path.relative(generatedRoot), true);
} }
} }
return; return;
...@@ -157,11 +158,11 @@ class MultirootFileBasedAssetReader extends core.FileBasedAssetReader { ...@@ -157,11 +158,11 @@ class MultirootFileBasedAssetReader extends core.FileBasedAssetReader {
} }
bool _missingSource(AssetId id) { bool _missingSource(AssetId id) {
return !fs.file(path.joinAll(<String>[packageGraph.root.path, ...id.pathSegments])).existsSync(); return !globals.fs.file(path.joinAll(<String>[packageGraph.root.path, ...id.pathSegments])).existsSync();
} }
File _generatedFile(AssetId id) { File _generatedFile(AssetId id) {
return fs.file( return globals.fs.file(
path.joinAll(<String>[generatedDirectory.path, packageGraph.root.name, ...id.pathSegments]) path.joinAll(<String>[generatedDirectory.path, packageGraph.root.name, ...id.pathSegments])
); );
} }
......
...@@ -12,11 +12,10 @@ import 'package:pool/pool.dart'; ...@@ -12,11 +12,10 @@ import 'package:pool/pool.dart';
import '../base/context.dart'; import '../base/context.dart';
import '../base/file_system.dart'; import '../base/file_system.dart';
import '../base/platform.dart';
import '../base/utils.dart'; import '../base/utils.dart';
import '../cache.dart'; import '../cache.dart';
import '../convert.dart'; import '../convert.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import 'exceptions.dart'; import 'exceptions.dart';
import 'file_hash_store.dart'; import 'file_hash_store.dart';
import 'source.dart'; import 'source.dart';
...@@ -256,7 +255,7 @@ abstract class Target { ...@@ -256,7 +255,7 @@ abstract class Target {
/// Use a hard-coded path or directory relative to the current working /// Use a hard-coded path or directory relative to the current working
/// directory to write an output file. /// directory to write an output file.
/// ///
/// fs.file('build/linux/out') /// globals.fs.file('build/linux/out')
/// ..createSync() /// ..createSync()
/// ..writeAsStringSync('output data'); /// ..writeAsStringSync('output data');
/// ///
...@@ -309,9 +308,9 @@ class Environment { ...@@ -309,9 +308,9 @@ class Environment {
projectDir: projectDir, projectDir: projectDir,
buildDir: buildDirectory, buildDir: buildDirectory,
rootBuildDir: rootBuildDir, rootBuildDir: rootBuildDir,
cacheDir: Cache.instance.getRoot(), cacheDir: globals.cache.getRoot(),
defines: defines, defines: defines,
flutterRootDir: fs.directory(Cache.flutterRoot), flutterRootDir: globals.fs.directory(Cache.flutterRoot),
); );
} }
...@@ -411,7 +410,7 @@ class BuildSystem { ...@@ -411,7 +410,7 @@ class BuildSystem {
environment.outputDir.createSync(recursive: true); environment.outputDir.createSync(recursive: true);
// Load file hash store from previous builds. // Load file hash store from previous builds.
final FileHashStore fileCache = FileHashStore(environment, fs) final FileHashStore fileCache = FileHashStore(environment, globals.fs)
..initialize(); ..initialize();
// Perform sanity checks on build. // Perform sanity checks on build.
...@@ -461,7 +460,7 @@ class BuildSystem { ...@@ -461,7 +460,7 @@ class BuildSystem {
/// An active instance of a build. /// An active instance of a build.
class _BuildInstance { class _BuildInstance {
_BuildInstance(this.environment, this.fileCache, this.buildSystemConfig) _BuildInstance(this.environment, this.fileCache, this.buildSystemConfig)
: resourcePool = Pool(buildSystemConfig.resourcePoolSize ?? platform?.numberOfProcessors ?? 1); : resourcePool = Pool(buildSystemConfig.resourcePoolSize ?? globals.platform?.numberOfProcessors ?? 1);
final BuildSystemConfig buildSystemConfig; final BuildSystemConfig buildSystemConfig;
final Pool resourcePool; final Pool resourcePool;
...@@ -523,13 +522,13 @@ class _BuildInstance { ...@@ -523,13 +522,13 @@ class _BuildInstance {
if (canSkip) { if (canSkip) {
skipped = true; skipped = true;
printTrace('Skipping target: ${node.target.name}'); globals.printTrace('Skipping target: ${node.target.name}');
updateGraph(); updateGraph();
return passed; return passed;
} }
printTrace('${node.target.name}: Starting due to ${node.invalidatedReasons}'); globals.printTrace('${node.target.name}: Starting due to ${node.invalidatedReasons}');
await node.target.build(environment); await node.target.build(environment);
printTrace('${node.target.name}: Complete'); globals.printTrace('${node.target.name}: Complete');
node.inputs node.inputs
..clear() ..clear()
...@@ -555,7 +554,7 @@ class _BuildInstance { ...@@ -555,7 +554,7 @@ class _BuildInstance {
if (outputFiles.containsKey(previousOutput)) { if (outputFiles.containsKey(previousOutput)) {
continue; continue;
} }
final File previousFile = fs.file(previousOutput); final File previousFile = globals.fs.file(previousOutput);
if (previousFile.existsSync()) { if (previousFile.existsSync()) {
previousFile.deleteSync(); previousFile.deleteSync();
} }
...@@ -769,7 +768,7 @@ class Node { ...@@ -769,7 +768,7 @@ class Node {
// if this isn't a current output file there is no reason to compute the hash. // if this isn't a current output file there is no reason to compute the hash.
continue; continue;
} }
final File file = fs.file(previousOutput); final File file = globals.fs.file(previousOutput);
if (!file.existsSync()) { if (!file.existsSync()) {
invalidatedReasons.add(InvalidatedReason.outputMissing); invalidatedReasons.add(InvalidatedReason.outputMissing);
_dirty = true; _dirty = true;
...@@ -794,7 +793,7 @@ class Node { ...@@ -794,7 +793,7 @@ class Node {
if (missingInputs.isNotEmpty) { if (missingInputs.isNotEmpty) {
_dirty = true; _dirty = true;
final String missingMessage = missingInputs.map((File file) => file.path).join(', '); final String missingMessage = missingInputs.map((File file) => file.path).join(', ');
printTrace('invalidated build due to missing files: $missingMessage'); globals.printTrace('invalidated build due to missing files: $missingMessage');
invalidatedReasons.add(InvalidatedReason.inputMissing); invalidatedReasons.add(InvalidatedReason.inputMissing);
} }
......
...@@ -3,8 +3,7 @@ ...@@ -3,8 +3,7 @@
// found in the LICENSE file. // found in the LICENSE file.
import '../base/file_system.dart'; import '../base/file_system.dart';
import '../base/platform.dart'; import '../globals.dart' as globals;
import '../globals.dart';
/// A class for representing depfile formats. /// A class for representing depfile formats.
class Depfile { class Depfile {
...@@ -18,7 +17,7 @@ class Depfile { ...@@ -18,7 +17,7 @@ class Depfile {
final String contents = file.readAsStringSync(); final String contents = file.readAsStringSync();
final List<String> colonSeparated = contents.split(': '); final List<String> colonSeparated = contents.split(': ');
if (colonSeparated.length != 2) { if (colonSeparated.length != 2) {
printError('Invalid depfile: ${file.path}'); globals.printError('Invalid depfile: ${file.path}');
return const Depfile(<File>[], <File>[]); return const Depfile(<File>[], <File>[]);
} }
final List<File> inputs = _processList(colonSeparated[1].trim()); final List<File> inputs = _processList(colonSeparated[1].trim());
...@@ -43,7 +42,7 @@ class Depfile { ...@@ -43,7 +42,7 @@ class Depfile {
if (fileUri.scheme != 'file') { if (fileUri.scheme != 'file') {
continue; continue;
} }
inputs.add(fs.file(fileUri)); inputs.add(globals.fs.file(fileUri));
} }
return Depfile(inputs, <File>[output]); return Depfile(inputs, <File>[output]);
} }
...@@ -74,7 +73,7 @@ class Depfile { ...@@ -74,7 +73,7 @@ class Depfile {
void _writeFilesToBuffer(List<File> files, StringBuffer buffer) { void _writeFilesToBuffer(List<File> files, StringBuffer buffer) {
for (File outputFile in files) { for (File outputFile in files) {
if (platform.isWindows) { if (globals.platform.isWindows) {
// Paths in a depfile have to be escaped on windows. // Paths in a depfile have to be escaped on windows.
final String escapedPath = outputFile.path.replaceAll(r'\', r'\\'); final String escapedPath = outputFile.path.replaceAll(r'\', r'\\');
buffer.write(' $escapedPath'); buffer.write(' $escapedPath');
...@@ -98,7 +97,7 @@ class Depfile { ...@@ -98,7 +97,7 @@ class Depfile {
// The tool doesn't write duplicates to these lists. This call is an attempt to // The tool doesn't write duplicates to these lists. This call is an attempt to
// be resillient to the outputs of other tools which write or user edits to depfiles. // be resillient to the outputs of other tools which write or user edits to depfiles.
.toSet() .toSet()
.map((String path) => fs.file(path)) .map((String path) => globals.fs.file(path))
.toList(); .toList();
} }
} }
...@@ -12,7 +12,7 @@ import 'package:pool/pool.dart'; ...@@ -12,7 +12,7 @@ import 'package:pool/pool.dart';
import '../base/file_system.dart'; import '../base/file_system.dart';
import '../base/utils.dart'; import '../base/utils.dart';
import '../convert.dart'; import '../convert.dart';
import '../globals.dart'; import '../globals.dart' as globals;
import 'build_system.dart'; import 'build_system.dart';
/// An encoded representation of all file hashes. /// An encoded representation of all file hashes.
...@@ -88,7 +88,7 @@ class FileHashStore { ...@@ -88,7 +88,7 @@ class FileHashStore {
/// Read file hashes from disk. /// Read file hashes from disk.
void initialize() { void initialize() {
printTrace('Initializing file store'); globals.printTrace('Initializing file store');
final File cacheFile = fileSystem.file(_cachePath); final File cacheFile = fileSystem.file(_cachePath);
if (!cacheFile.existsSync()) { if (!cacheFile.existsSync()) {
return; return;
...@@ -97,7 +97,7 @@ class FileHashStore { ...@@ -97,7 +97,7 @@ class FileHashStore {
try { try {
data = cacheFile.readAsBytesSync(); data = cacheFile.readAsBytesSync();
} on FileSystemException catch (err) { } on FileSystemException catch (err) {
printError( globals.printError(
'Failed to read file store at ${cacheFile.path} due to $err.\n' 'Failed to read file store at ${cacheFile.path} due to $err.\n'
'Build artifacts will not be cached. Try clearing the cache directories ' 'Build artifacts will not be cached. Try clearing the cache directories '
'with "flutter clean"', 'with "flutter clean"',
...@@ -109,24 +109,24 @@ class FileHashStore { ...@@ -109,24 +109,24 @@ class FileHashStore {
try { try {
fileStorage = FileStorage.fromBuffer(data); fileStorage = FileStorage.fromBuffer(data);
} catch (err) { } catch (err) {
printTrace('Filestorage format changed'); globals.printTrace('Filestorage format changed');
cacheFile.deleteSync(); cacheFile.deleteSync();
return; return;
} }
if (fileStorage.version != _kVersion) { if (fileStorage.version != _kVersion) {
printTrace('file cache format updating, clearing old hashes.'); globals.printTrace('file cache format updating, clearing old hashes.');
cacheFile.deleteSync(); cacheFile.deleteSync();
return; return;
} }
for (FileHash fileHash in fileStorage.files) { for (FileHash fileHash in fileStorage.files) {
previousHashes[fileHash.path] = fileHash.hash; previousHashes[fileHash.path] = fileHash.hash;
} }
printTrace('Done initializing file store'); globals.printTrace('Done initializing file store');
} }
/// Persist file hashes to disk. /// Persist file hashes to disk.
void persist() { void persist() {
printTrace('Persisting file store'); globals.printTrace('Persisting file store');
final File cacheFile = fileSystem.file(_cachePath); final File cacheFile = fileSystem.file(_cachePath);
if (!cacheFile.existsSync()) { if (!cacheFile.existsSync()) {
cacheFile.createSync(recursive: true); cacheFile.createSync(recursive: true);
...@@ -143,13 +143,13 @@ class FileHashStore { ...@@ -143,13 +143,13 @@ class FileHashStore {
try { try {
cacheFile.writeAsBytesSync(buffer); cacheFile.writeAsBytesSync(buffer);
} on FileSystemException catch (err) { } on FileSystemException catch (err) {
printError( globals.printError(
'Failed to persist file store at ${cacheFile.path} due to $err.\n' 'Failed to persist file store at ${cacheFile.path} due to $err.\n'
'Build artifacts will not be cached. Try clearing the cache directories ' 'Build artifacts will not be cached. Try clearing the cache directories '
'with "flutter clean"', 'with "flutter clean"',
); );
} }
printTrace('Done persisting file store'); globals.printTrace('Done persisting file store');
} }
/// Computes a hash of the provided files and returns a list of entities /// Computes a hash of the provided files and returns a list of entities
......
...@@ -6,7 +6,7 @@ import '../../artifacts.dart'; ...@@ -6,7 +6,7 @@ import '../../artifacts.dart';
import '../../base/build.dart'; import '../../base/build.dart';
import '../../base/file_system.dart'; import '../../base/file_system.dart';
import '../../build_info.dart'; import '../../build_info.dart';
import '../../globals.dart'; import '../../globals.dart' as globals;
import '../build_system.dart'; import '../build_system.dart';
import '../depfile.dart'; import '../depfile.dart';
import '../exceptions.dart'; import '../exceptions.dart';
...@@ -50,13 +50,13 @@ abstract class AndroidAssetBundle extends Target { ...@@ -50,13 +50,13 @@ abstract class AndroidAssetBundle extends Target {
// Only copy the prebuilt runtimes and kernel blob in debug mode. // Only copy the prebuilt runtimes and kernel blob in debug mode.
if (buildMode == BuildMode.debug) { if (buildMode == BuildMode.debug) {
final String vmSnapshotData = artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug); final String vmSnapshotData = globals.artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug);
final String isolateSnapshotData = artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug); final String isolateSnapshotData = globals.artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug);
environment.buildDir.childFile('app.dill') environment.buildDir.childFile('app.dill')
.copySync(outputDirectory.childFile('kernel_blob.bin').path); .copySync(outputDirectory.childFile('kernel_blob.bin').path);
fs.file(vmSnapshotData) globals.fs.file(vmSnapshotData)
.copySync(outputDirectory.childFile('vm_snapshot_data').path); .copySync(outputDirectory.childFile('vm_snapshot_data').path);
fs.file(isolateSnapshotData) globals.fs.file(isolateSnapshotData)
.copySync(outputDirectory.childFile('isolate_snapshot_data').path); .copySync(outputDirectory.childFile('isolate_snapshot_data').path);
} }
if (_copyAssets) { if (_copyAssets) {
......
...@@ -7,6 +7,7 @@ import 'package:pool/pool.dart'; ...@@ -7,6 +7,7 @@ import 'package:pool/pool.dart';
import '../../asset.dart'; import '../../asset.dart';
import '../../base/file_system.dart'; import '../../base/file_system.dart';
import '../../devfs.dart'; import '../../devfs.dart';
import '../../globals.dart' as globals;
import '../../plugins.dart'; import '../../plugins.dart';
import '../../project.dart'; import '../../project.dart';
import '../build_system.dart'; import '../build_system.dart';
...@@ -39,12 +40,12 @@ Future<Depfile> copyAssets(Environment environment, Directory outputDirectory) a ...@@ -39,12 +40,12 @@ Future<Depfile> copyAssets(Environment environment, Directory outputDirectory) a
// to `%23.ext`. However, we have to keep it this way since the // to `%23.ext`. However, we have to keep it this way since the
// platform channels in the framework will URI encode these values, // platform channels in the framework will URI encode these values,
// and the native APIs will look for files this way. // and the native APIs will look for files this way.
final File file = fs.file(fs.path.join(outputDirectory.path, entry.key)); final File file = globals.fs.file(globals.fs.path.join(outputDirectory.path, entry.key));
outputs.add(file); outputs.add(file);
file.parent.createSync(recursive: true); file.parent.createSync(recursive: true);
final DevFSContent content = entry.value; final DevFSContent content = entry.value;
if (content is DevFSFileContent && content.file is File) { if (content is DevFSFileContent && content.file is File) {
inputs.add(fs.file(content.file.path)); inputs.add(globals.fs.file(content.file.path));
await (content.file as File).copy(file.path); await (content.file as File).copy(file.path);
} else { } else {
await file.writeAsBytes(await entry.value.contentsAsBytes()); await file.writeAsBytes(await entry.value.contentsAsBytes());
......
...@@ -8,7 +8,7 @@ import '../../base/file_system.dart'; ...@@ -8,7 +8,7 @@ import '../../base/file_system.dart';
import '../../build_info.dart'; import '../../build_info.dart';
import '../../compile.dart'; import '../../compile.dart';
import '../../convert.dart'; import '../../convert.dart';
import '../../globals.dart'; import '../../globals.dart' as globals;
import '../../project.dart'; import '../../project.dart';
import '../build_system.dart'; import '../build_system.dart';
import '../depfile.dart'; import '../depfile.dart';
...@@ -99,13 +99,13 @@ class CopyFlutterBundle extends Target { ...@@ -99,13 +99,13 @@ class CopyFlutterBundle extends Target {
// Only copy the prebuilt runtimes and kernel blob in debug mode. // Only copy the prebuilt runtimes and kernel blob in debug mode.
if (buildMode == BuildMode.debug) { if (buildMode == BuildMode.debug) {
final String vmSnapshotData = artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug); final String vmSnapshotData = globals.artifacts.getArtifactPath(Artifact.vmSnapshotData, mode: BuildMode.debug);
final String isolateSnapshotData = artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug); final String isolateSnapshotData = globals.artifacts.getArtifactPath(Artifact.isolateSnapshotData, mode: BuildMode.debug);
environment.buildDir.childFile('app.dill') environment.buildDir.childFile('app.dill')
.copySync(environment.outputDir.childFile('kernel_blob.bin').path); .copySync(environment.outputDir.childFile('kernel_blob.bin').path);
fs.file(vmSnapshotData) globals.fs.file(vmSnapshotData)
.copySync(environment.outputDir.childFile('vm_snapshot_data').path); .copySync(environment.outputDir.childFile('vm_snapshot_data').path);
fs.file(isolateSnapshotData) globals.fs.file(isolateSnapshotData)
.copySync(environment.outputDir.childFile('isolate_snapshot_data').path); .copySync(environment.outputDir.childFile('isolate_snapshot_data').path);
} }
final Depfile assetDepfile = await copyAssets(environment, environment.outputDir); final Depfile assetDepfile = await copyAssets(environment, environment.outputDir);
...@@ -180,9 +180,9 @@ class KernelSnapshot extends Target { ...@@ -180,9 +180,9 @@ class KernelSnapshot extends Target {
throw MissingDefineException(kTargetPlatform, 'kernel_snapshot'); throw MissingDefineException(kTargetPlatform, 'kernel_snapshot');
} }
final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]); final BuildMode buildMode = getBuildModeForName(environment.defines[kBuildMode]);
final String targetFile = environment.defines[kTargetFile] ?? fs.path.join('lib', 'main.dart'); final String targetFile = environment.defines[kTargetFile] ?? globals.fs.path.join('lib', 'main.dart');
final String packagesPath = environment.projectDir.childFile('.packages').path; final String packagesPath = environment.projectDir.childFile('.packages').path;
final String targetFileAbsolute = fs.file(targetFile).absolute.path; final String targetFileAbsolute = globals.fs.file(targetFile).absolute.path;
// everything besides 'false' is considered to be enabled. // everything besides 'false' is considered to be enabled.
final bool trackWidgetCreation = environment.defines[kTrackWidgetCreation] != 'false'; final bool trackWidgetCreation = environment.defines[kTrackWidgetCreation] != 'false';
final TargetPlatform targetPlatform = getTargetPlatformForName(environment.defines[kTargetPlatform]); final TargetPlatform targetPlatform = getTargetPlatformForName(environment.defines[kTargetPlatform]);
...@@ -214,7 +214,7 @@ class KernelSnapshot extends Target { ...@@ -214,7 +214,7 @@ class KernelSnapshot extends Target {
} }
final CompilerOutput output = await compiler.compile( final CompilerOutput output = await compiler.compile(
sdkRoot: artifacts.getArtifactPath( sdkRoot: globals.artifacts.getArtifactPath(
Artifact.flutterPatchedSdkPath, Artifact.flutterPatchedSdkPath,
platform: targetPlatform, platform: targetPlatform,
mode: buildMode, mode: buildMode,
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
import 'dart:async'; import 'dart:async';
import '../base/file_system.dart'; import '../base/file_system.dart';
import '../globals.dart' as globals;
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';
...@@ -72,7 +73,7 @@ class AnalyzeCommand extends FlutterCommand { ...@@ -72,7 +73,7 @@ class AnalyzeCommand extends FlutterCommand {
} }
// Or we're not in a project directory. // Or we're not in a project directory.
if (!fs.file('pubspec.yaml').existsSync()) { if (!globals.fs.file('pubspec.yaml').existsSync()) {
return false; return false;
} }
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment