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