[flutter_tools] Ensure that global variables are easily identifiable (#47398)
diff --git a/packages/flutter_tools/lib/src/commands/analyze.dart b/packages/flutter_tools/lib/src/commands/analyze.dart index c4123c0..a3661a1 100644 --- a/packages/flutter_tools/lib/src/commands/analyze.dart +++ b/packages/flutter_tools/lib/src/commands/analyze.dart
@@ -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 @@ } // Or we're not in a project directory. - if (!fs.file('pubspec.yaml').existsSync()) { + if (!globals.fs.file('pubspec.yaml').existsSync()) { return false; }
diff --git a/packages/flutter_tools/lib/src/commands/analyze_base.dart b/packages/flutter_tools/lib/src/commands/analyze_base.dart index 32c7aad..568e117 100644 --- a/packages/flutter_tools/lib/src/commands/analyze_base.dart +++ b/packages/flutter_tools/lib/src/commands/analyze_base.dart
@@ -11,7 +11,7 @@ import '../base/file_system.dart'; import '../base/utils.dart'; import '../cache.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; /// Common behavior for `flutter analyze` and `flutter analyze --watch` abstract class AnalyzeBase { @@ -26,7 +26,7 @@ void dumpErrors(Iterable<String> errors) { if (argResults['write'] != null) { try { - final RandomAccessFile resultsFile = fs.file(argResults['write']).openSync(mode: FileMode.write); + final RandomAccessFile resultsFile = globals.fs.file(argResults['write']).openSync(mode: FileMode.write); try { resultsFile.lockSync(); resultsFile.writeStringSync(errors.join('\n')); @@ -34,7 +34,7 @@ resultsFile.close(); } } catch (e) { - printError('Failed to save output to "${argResults['write']}": $e'); + globals.printError('Failed to save output to "${argResults['write']}": $e'); } } } @@ -46,8 +46,8 @@ 'issues': errorCount, 'missingDartDocs': membersMissingDocumentation, }; - fs.file(benchmarkOut).writeAsStringSync(toPrettyJson(data)); - printStatus('Analysis benchmark written to $benchmarkOut ($data).'); + globals.fs.file(benchmarkOut).writeAsStringSync(toPrettyJson(data)); + globals.printStatus('Analysis benchmark written to $benchmarkOut ($data).'); } bool get isBenchmarking => argResults['benchmark'] as bool; @@ -57,12 +57,12 @@ /// If [fileList] is empty, then return true if the current directory resides inside the Flutter repository. bool inRepo(List<String> fileList) { if (fileList == null || fileList.isEmpty) { - fileList = <String>[fs.path.current]; + fileList = <String>[globals.fs.path.current]; } - final String root = fs.path.normalize(fs.path.absolute(Cache.flutterRoot)); - final String prefix = root + fs.path.separator; + final String root = globals.fs.path.normalize(globals.fs.path.absolute(Cache.flutterRoot)); + final String prefix = root + globals.fs.path.separator; for (String file in fileList) { - file = fs.path.normalize(fs.path.absolute(file)); + file = globals.fs.path.normalize(globals.fs.path.absolute(file)); if (file == root || file.startsWith(prefix)) { return true; } @@ -85,11 +85,11 @@ } bool get hasConflict => values.length > 1; bool get hasConflictAffectingFlutterRepo { - assert(fs.path.isAbsolute(Cache.flutterRoot)); + assert(globals.fs.path.isAbsolute(Cache.flutterRoot)); for (List<String> targetSources in values.values) { for (String source in targetSources) { - assert(fs.path.isAbsolute(source)); - if (fs.path.isWithin(Cache.flutterRoot, source)) { + assert(globals.fs.path.isAbsolute(source)); + if (globals.fs.path.isWithin(Cache.flutterRoot, source)) { return true; } } @@ -132,8 +132,8 @@ /// Read the .packages file in [directory] and add referenced packages to [dependencies]. void addDependenciesFromPackagesFileIn(Directory directory) { - final String dotPackagesPath = fs.path.join(directory.path, '.packages'); - final File dotPackages = fs.file(dotPackagesPath); + final String dotPackagesPath = globals.fs.path.join(directory.path, '.packages'); + final File dotPackages = globals.fs.file(dotPackagesPath); if (dotPackages.existsSync()) { // this directory has opinions about what we should be using final Iterable<String> lines = dotPackages @@ -144,12 +144,12 @@ final int colon = line.indexOf(':'); if (colon > 0) { final String packageName = line.substring(0, colon); - final String packagePath = fs.path.fromUri(line.substring(colon+1)); + final String packagePath = globals.fs.path.fromUri(line.substring(colon+1)); // Ensure that we only add `analyzer` and dependent packages defined in the vended SDK (and referred to with a local - // fs.path. directive). Analyzer package versions reached via transitive dependencies (e.g., via `test`) are ignored + // globals.fs.path. directive). Analyzer package versions reached via transitive dependencies (e.g., via `test`) are ignored // since they would produce spurious conflicts. if (!_vendedSdkPackages.contains(packageName) || packagePath.startsWith('..')) { - add(packageName, fs.path.normalize(fs.path.absolute(directory.path, packagePath)), dotPackagesPath); + add(packageName, globals.fs.path.normalize(globals.fs.path.absolute(directory.path, packagePath)), dotPackagesPath); } } } @@ -166,17 +166,17 @@ void checkForConflictingDependencies(Iterable<Directory> pubSpecDirectories, PackageDependencyTracker dependencies) { for (Directory directory in pubSpecDirectories) { - final String pubSpecYamlPath = fs.path.join(directory.path, 'pubspec.yaml'); - final File pubSpecYamlFile = fs.file(pubSpecYamlPath); + final String pubSpecYamlPath = globals.fs.path.join(directory.path, 'pubspec.yaml'); + final File pubSpecYamlFile = globals.fs.file(pubSpecYamlPath); if (pubSpecYamlFile.existsSync()) { // we are analyzing the actual canonical source for this package; // make sure we remember that, in case all the packages are actually // pointing elsewhere somehow. - final dynamic pubSpecYaml = yaml.loadYaml(fs.file(pubSpecYamlPath).readAsStringSync()); + final dynamic pubSpecYaml = yaml.loadYaml(globals.fs.file(pubSpecYamlPath).readAsStringSync()); if (pubSpecYaml is yaml.YamlMap) { final dynamic packageName = pubSpecYaml['name']; if (packageName is String) { - final String packagePath = fs.path.normalize(fs.path.absolute(fs.path.join(directory.path, 'lib'))); + final String packagePath = globals.fs.path.normalize(globals.fs.path.absolute(globals.fs.path.join(directory.path, 'lib'))); dependencies.addCanonicalCase(packageName, packagePath, pubSpecYamlPath); } else { throwToolExit('pubspec.yaml is malformed. The name should be a String.');
diff --git a/packages/flutter_tools/lib/src/commands/analyze_continuously.dart b/packages/flutter_tools/lib/src/commands/analyze_continuously.dart index 89d386f..2e9802c 100644 --- a/packages/flutter_tools/lib/src/commands/analyze_continuously.dart +++ b/packages/flutter_tools/lib/src/commands/analyze_continuously.dart
@@ -10,12 +10,11 @@ import '../base/file_system.dart'; import '../base/io.dart'; import '../base/logger.dart'; -import '../base/terminal.dart'; import '../base/utils.dart'; import '../cache.dart'; import '../dart/analysis.dart'; import '../dart/sdk.dart' as sdk; -import '../globals.dart'; +import '../globals.dart' as globals; import 'analyze_base.dart'; class AnalyzeContinuously extends AnalyzeBase { @@ -43,13 +42,13 @@ directories = repoRoots; analysisTarget = 'Flutter repository'; - printTrace('Analyzing Flutter repository:'); + globals.printTrace('Analyzing Flutter repository:'); for (String projectPath in repoRoots) { - printTrace(' ${fs.path.relative(projectPath)}'); + globals.printTrace(' ${globals.fs.path.relative(projectPath)}'); } } else { - directories = <String>[fs.currentDirectory.path]; - analysisTarget = fs.currentDirectory.path; + directories = <String>[globals.fs.currentDirectory.path]; + analysisTarget = globals.fs.currentDirectory.path; } final String sdkPath = argResults['dart-sdk'] as String ?? sdk.dartSdkPath; @@ -67,7 +66,7 @@ if (exitCode != 0) { throwToolExit(message, exitCode: exitCode); } - printStatus(message); + globals.printStatus(message); if (server.didServerErrorOccur) { throwToolExit('Server error(s) occurred.'); @@ -78,9 +77,9 @@ if (isAnalyzing) { analysisStatus?.cancel(); if (!firstAnalysis) { - printStatus('\n'); + globals.printStatus('\n'); } - analysisStatus = logger.startProgress('Analyzing $analysisTarget...', timeout: timeoutConfiguration.slowOperation); + analysisStatus = globals.logger.startProgress('Analyzing $analysisTarget...', timeout: timeoutConfiguration.slowOperation); analyzedPaths.clear(); analysisTimer = Stopwatch()..start(); } else { @@ -88,12 +87,12 @@ analysisStatus = null; analysisTimer.stop(); - logger.printStatus(terminal.clearScreen(), newline: false); + globals.logger.printStatus(globals.terminal.clearScreen(), newline: false); // Remove errors for deleted files, sort, and print errors. final List<AnalysisError> errors = <AnalysisError>[]; for (String path in analysisErrors.keys.toList()) { - if (fs.isFileSync(path)) { + if (globals.fs.isFileSync(path)) { errors.addAll(analysisErrors[path]); } else { analysisErrors.remove(path); @@ -114,9 +113,9 @@ errors.sort(); for (AnalysisError error in errors) { - printStatus(error.toString()); + globals.printStatus(error.toString()); if (error.code != null) { - printTrace('error code: ${error.code}'); + globals.printTrace('error code: ${error.code}'); } } @@ -149,9 +148,9 @@ final String files = '${analyzedPaths.length} ${pluralize('file', analyzedPaths.length)}'; final String seconds = (analysisTimer.elapsedMilliseconds / 1000.0).toStringAsFixed(2); if (undocumentedMembers > 0) { - printStatus('$errorsMessage • $dartdocMessage • analyzed $files in $seconds seconds'); + globals.printStatus('$errorsMessage • $dartdocMessage • analyzed $files in $seconds seconds'); } else { - printStatus('$errorsMessage • analyzed $files in $seconds seconds'); + globals.printStatus('$errorsMessage • analyzed $files in $seconds seconds'); } if (firstAnalysis && isBenchmarking) {
diff --git a/packages/flutter_tools/lib/src/commands/analyze_once.dart b/packages/flutter_tools/lib/src/commands/analyze_once.dart index c339a49..aaa44df 100644 --- a/packages/flutter_tools/lib/src/commands/analyze_once.dart +++ b/packages/flutter_tools/lib/src/commands/analyze_once.dart
@@ -13,7 +13,7 @@ import '../cache.dart'; import '../dart/analysis.dart'; import '../dart/sdk.dart' as sdk; -import '../globals.dart'; +import '../globals.dart' as globals; import 'analyze.dart'; import 'analyze_base.dart'; @@ -35,14 +35,14 @@ @override Future<void> analyze() async { final String currentDirectory = - (workingDirectory ?? fs.currentDirectory).path; + (workingDirectory ?? globals.fs.currentDirectory).path; // find directories from argResults.rest final Set<String> directories = Set<String>.from(argResults.rest - .map<String>((String path) => fs.path.canonicalize(path))); + .map<String>((String path) => globals.fs.path.canonicalize(path))); if (directories.isNotEmpty) { for (String directory in directories) { - final FileSystemEntityType type = fs.typeSync(directory); + final FileSystemEntityType type = globals.fs.typeSync(directory); if (type == FileSystemEntityType.notFound) { throwToolExit("'$directory' does not exist"); @@ -108,9 +108,9 @@ final Stopwatch timer = Stopwatch()..start(); final String message = directories.length > 1 ? '${directories.length} ${directories.length == 1 ? 'directory' : 'directories'}' - : fs.path.basename(directories.first); + : globals.fs.path.basename(directories.first); final Status progress = argResults['preamble'] as bool - ? logger.startProgress('Analyzing $message...', timeout: timeoutConfiguration.slowOperation) + ? globals.logger.startProgress('Analyzing $message...', timeout: timeoutConfiguration.slowOperation) : null; await analysisCompleter.future; @@ -135,11 +135,11 @@ // report errors if (errors.isNotEmpty && (argResults['preamble'] as bool)) { - printStatus(''); + globals.printStatus(''); } errors.sort(); for (AnalysisError error in errors) { - printStatus(error.toString(), hangingIndent: 7); + globals.printStatus(error.toString(), hangingIndent: 7); } final String seconds = (timer.elapsedMilliseconds / 1000.0).toStringAsFixed(1); @@ -154,7 +154,7 @@ // We consider any level of error to be an error exit (we don't report different levels). if (errors.isNotEmpty) { final int errorCount = errors.length; - printStatus(''); + globals.printStatus(''); if (undocumentedMembers > 0) { throwToolExit('$errorCount ${pluralize('issue', errorCount)} found. (ran in ${seconds}s; $dartdocMessage)'); } else { @@ -168,9 +168,9 @@ if (argResults['congratulate'] as bool) { if (undocumentedMembers > 0) { - printStatus('No issues found! (ran in ${seconds}s; $dartdocMessage)'); + globals.printStatus('No issues found! (ran in ${seconds}s; $dartdocMessage)'); } else { - printStatus('No issues found! (ran in ${seconds}s)'); + globals.printStatus('No issues found! (ran in ${seconds}s)'); } } }
diff --git a/packages/flutter_tools/lib/src/commands/assemble.dart b/packages/flutter_tools/lib/src/commands/assemble.dart index 0c6fbda..583412b 100644 --- a/packages/flutter_tools/lib/src/commands/assemble.dart +++ b/packages/flutter_tools/lib/src/commands/assemble.dart
@@ -16,7 +16,7 @@ import '../build_system/targets/macos.dart'; import '../build_system/targets/web.dart'; import '../build_system/targets/windows.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../project.dart'; import '../reporting/reporting.dart'; import '../runner/flutter_command.dart'; @@ -137,11 +137,11 @@ throwToolExit('--output directory is required for assemble.'); } // If path is relative, make it absolute from flutter project. - if (fs.path.isRelative(output)) { - output = fs.path.join(flutterProject.directory.path, output); + if (globals.fs.path.isRelative(output)) { + output = globals.fs.path.join(flutterProject.directory.path, output); } final Environment result = Environment( - outputDir: fs.directory(output), + outputDir: globals.fs.directory(output), buildDir: flutterProject.directory .childDirectory('.dart_tool') .childDirectory('flutter_build'), @@ -180,7 +180,7 @@ )); 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, @@ -188,7 +188,7 @@ } throwToolExit('build failed.'); } - printTrace('build succeeded.'); + globals.printTrace('build succeeded.'); if (argResults.wasParsed('build-inputs')) { writeListIfChanged(result.inputFiles, stringArg('build-inputs')); } @@ -196,9 +196,9 @@ writeListIfChanged(result.outputFiles, stringArg('build-outputs')); } if (argResults.wasParsed('depfile')) { - final File depfileFile = fs.file(stringArg('depfile')); + final File depfileFile = globals.fs.file(stringArg('depfile')); final Depfile depfile = Depfile(result.inputFiles, result.outputFiles); - depfile.writeToFile(fs.file(depfileFile)); + depfile.writeToFile(globals.fs.file(depfileFile)); } return null; } @@ -206,7 +206,7 @@ @visibleForTesting void writeListIfChanged(List<File> files, String path) { - final File file = fs.file(path); + final File file = globals.fs.file(path); final StringBuffer buffer = StringBuffer(); // These files are already sorted. for (File file in files) {
diff --git a/packages/flutter_tools/lib/src/commands/attach.dart b/packages/flutter_tools/lib/src/commands/attach.dart index da717c3..3ce4a89 100644 --- a/packages/flutter_tools/lib/src/commands/attach.dart +++ b/packages/flutter_tools/lib/src/commands/attach.dart
@@ -11,14 +11,13 @@ import '../base/context.dart'; import '../base/file_system.dart'; import '../base/io.dart'; -import '../base/terminal.dart'; import '../base/utils.dart'; import '../cache.dart'; import '../commands/daemon.dart'; import '../compile.dart'; import '../device.dart'; import '../fuchsia/fuchsia_device.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../ios/devices.dart'; import '../ios/simulators.dart'; import '../mdns_discovery.dart'; @@ -172,11 +171,11 @@ final Device device = await findTargetDevice(); - final Artifacts artifacts = device.artifactOverrides ?? Artifacts.instance; + final Artifacts overrideArtifacts = device.artifactOverrides ?? globals.artifacts; await context.run<void>( body: () => _attachToDevice(device), overrides: <Type, Generator>{ - Artifacts: () => artifacts, + Artifacts: () => overrideArtifacts, }); return null; @@ -254,7 +253,7 @@ devicePort: deviceVmservicePort, hostPort: hostVmservicePort, ); - printStatus('Waiting for a connection from Flutter on ${device.name}...'); + globals.printStatus('Waiting for a connection from Flutter on ${device.name}...'); observatoryUri = observatoryDiscovery.uris; // Determine ipv6 status from the scanned logs. usesIpv6 = observatoryDiscovery.ipv6; @@ -272,7 +271,7 @@ ).asBroadcastStream(); } - terminal.usesTerminalUi = daemon == null; + globals.terminal.usesTerminalUi = daemon == null; try { int result; @@ -291,7 +290,7 @@ device, null, true, - fs.currentDirectory, + globals.fs.currentDirectory, LaunchMode.attach, ); } catch (error) { @@ -326,7 +325,7 @@ if (runner.exited || !runner.isWaitingForObservatory) { break; } - printStatus('Waiting for a new connection from Flutter on ${device.name}...'); + globals.printStatus('Waiting for a new connection from Flutter on ${device.name}...'); } } finally { final List<ForwardedPort> ports = device.portForwarder.forwardedPorts.toList();
diff --git a/packages/flutter_tools/lib/src/commands/build_apk.dart b/packages/flutter_tools/lib/src/commands/build_apk.dart index 05948bc..3307656 100644 --- a/packages/flutter_tools/lib/src/commands/build_apk.dart +++ b/packages/flutter_tools/lib/src/commands/build_apk.dart
@@ -10,7 +10,7 @@ import '../base/terminal.dart'; import '../build_info.dart'; import '../cache.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../project.dart'; import '../reporting/reporting.dart'; import '../runner/flutter_command.dart' show FlutterCommandResult; @@ -93,19 +93,19 @@ if (buildInfo.isRelease && !androidBuildInfo.splitPerAbi && androidBuildInfo.targetArchs.length > 1) { final String targetPlatforms = stringsArg('target-platform').join(', '); - printStatus('You are building a fat APK that includes binaries for ' + globals.printStatus('You are building a fat APK that includes binaries for ' '$targetPlatforms.', emphasis: true, color: TerminalColor.green); - printStatus('If you are deploying the app to the Play Store, ' + globals.printStatus('If you are deploying the app to the Play Store, ' 'it\'s recommended to use app bundles or split the APK to reduce the APK size.', emphasis: true); - printStatus('To generate an app bundle, run:', emphasis: true, indent: 4); - printStatus('flutter build appbundle ' + globals.printStatus('To generate an app bundle, run:', emphasis: true, indent: 4); + globals.printStatus('flutter build appbundle ' '--target-platform ${targetPlatforms.replaceAll(' ', '')}',indent: 8); - printStatus('Learn more on: https://developer.android.com/guide/app-bundle',indent: 8); - printStatus('To split the APKs per ABI, run:', emphasis: true, indent: 4); - printStatus('flutter build apk ' + globals.printStatus('Learn more on: https://developer.android.com/guide/app-bundle',indent: 8); + globals.printStatus('To split the APKs per ABI, run:', emphasis: true, indent: 4); + globals.printStatus('flutter build apk ' '--target-platform ${targetPlatforms.replaceAll(' ', '')} ' '--split-per-abi', indent: 8); - printStatus('Learn more on: https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split',indent: 8); + globals.printStatus('Learn more on: https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split',indent: 8); } await androidBuilder.buildApk( project: FlutterProject.current(),
diff --git a/packages/flutter_tools/lib/src/commands/build_bundle.dart b/packages/flutter_tools/lib/src/commands/build_bundle.dart index 78b3747..90b1c73 100644 --- a/packages/flutter_tools/lib/src/commands/build_bundle.dart +++ b/packages/flutter_tools/lib/src/commands/build_bundle.dart
@@ -5,10 +5,10 @@ import 'dart:async'; import '../base/common.dart'; -import '../base/file_system.dart'; import '../build_info.dart'; import '../bundle.dart'; import '../features.dart'; +import '../globals.dart' as globals; import '../project.dart'; import '../reporting/reporting.dart'; import '../runner/flutter_command.dart' show FlutterOptions, FlutterCommandResult; @@ -82,7 +82,7 @@ @override Future<Map<CustomDimensions, String>> get usageValues async { - final String projectDir = fs.file(targetFile).parent.parent.path; + final String projectDir = globals.fs.file(targetFile).parent.parent.path; final FlutterProject futterProject = FlutterProject.fromPath(projectDir); if (futterProject == null) { return const <CustomDimensions, String>{};
diff --git a/packages/flutter_tools/lib/src/commands/build_fuchsia.dart b/packages/flutter_tools/lib/src/commands/build_fuchsia.dart index c64f128..b0a8c71 100644 --- a/packages/flutter_tools/lib/src/commands/build_fuchsia.dart +++ b/packages/flutter_tools/lib/src/commands/build_fuchsia.dart
@@ -5,11 +5,11 @@ import 'dart:async'; import '../base/common.dart'; -import '../base/platform.dart'; import '../build_info.dart'; import '../cache.dart'; import '../fuchsia/fuchsia_build.dart'; import '../fuchsia/fuchsia_pm.dart'; +import '../globals.dart' as globals; import '../project.dart'; import '../runner/flutter_command.dart' show FlutterCommandResult; import 'build.dart'; @@ -56,7 +56,7 @@ Cache.releaseLockEarly(); final BuildInfo buildInfo = getBuildInfo(); final FlutterProject flutterProject = FlutterProject.current(); - if (!platform.isLinux && !platform.isMacOS) { + if (!globals.platform.isLinux && !globals.platform.isMacOS) { throwToolExit('"build fuchsia" is only supported on Linux and MacOS hosts.'); } if (!flutterProject.fuchsia.existsSync()) {
diff --git a/packages/flutter_tools/lib/src/commands/build_ios.dart b/packages/flutter_tools/lib/src/commands/build_ios.dart index 62849ee..3f28e77 100644 --- a/packages/flutter_tools/lib/src/commands/build_ios.dart +++ b/packages/flutter_tools/lib/src/commands/build_ios.dart
@@ -6,10 +6,9 @@ import '../application_package.dart'; import '../base/common.dart'; -import '../base/platform.dart'; import '../base/utils.dart'; import '../build_info.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../ios/mac.dart'; import '../runner/flutter_command.dart' show DevelopmentArtifact, FlutterCommandResult; import 'build.dart'; @@ -51,7 +50,7 @@ final bool forSimulator = boolArg('simulator'); defaultBuildMode = forSimulator ? BuildMode.debug : BuildMode.release; - if (!platform.isMacOS) { + if (!globals.platform.isMacOS) { throwToolExit('Building for iOS is only supported on the Mac.'); } @@ -64,7 +63,7 @@ final bool shouldCodesign = boolArg('codesign'); if (!forSimulator && !shouldCodesign) { - printStatus('Warning: Building for device with codesigning disabled. You will ' + globals.printStatus('Warning: Building for device with codesigning disabled. You will ' 'have to manually codesign before deploying to device.'); } final BuildInfo buildInfo = getBuildInfo(); @@ -74,8 +73,8 @@ final String logTarget = forSimulator ? 'simulator' : 'device'; - final String typeName = artifacts.getEngineType(TargetPlatform.ios, buildInfo.mode); - printStatus('Building $app for $logTarget ($typeName)...'); + final String typeName = globals.artifacts.getEngineType(TargetPlatform.ios, buildInfo.mode); + globals.printStatus('Building $app for $logTarget ($typeName)...'); final XcodeBuildResult result = await buildXcodeProject( app: app, buildInfo: buildInfo, @@ -90,7 +89,7 @@ } if (result.output != null) { - printStatus('Built ${result.output}.'); + globals.printStatus('Built ${result.output}.'); } return null;
diff --git a/packages/flutter_tools/lib/src/commands/build_ios_framework.dart b/packages/flutter_tools/lib/src/commands/build_ios_framework.dart index 0cf45b1..bd48a12 100644 --- a/packages/flutter_tools/lib/src/commands/build_ios_framework.dart +++ b/packages/flutter_tools/lib/src/commands/build_ios_framework.dart
@@ -13,14 +13,13 @@ import '../base/common.dart'; import '../base/file_system.dart'; import '../base/logger.dart'; -import '../base/platform.dart'; import '../base/process.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../build_system/targets/ios.dart'; import '../bundle.dart'; import '../cache.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../macos/cocoapod_utils.dart'; import '../macos/xcode.dart'; import '../plugins.dart'; @@ -121,7 +120,7 @@ throwToolExit('Building frameworks for iOS is only supported from a module.'); } - if (!platform.isMacOS) { + if (!globals.platform.isMacOS) { throwToolExit('Building frameworks for iOS is only supported on the Mac.'); } @@ -141,7 +140,7 @@ Cache.releaseLockEarly(); final String outputArgument = stringArg('output') - ?? fs.path.join(fs.currentDirectory.path, 'build', 'ios', 'framework'); + ?? globals.fs.path.join(globals.fs.currentDirectory.path, 'build', 'ios', 'framework'); if (outputArgument.isEmpty) { throwToolExit('--output is required.'); @@ -153,14 +152,14 @@ throwToolExit("Module's iOS folder missing"); } - final Directory outputDirectory = fs.directory(fs.path.absolute(fs.path.normalize(outputArgument))); + final Directory outputDirectory = globals.fs.directory(globals.fs.path.absolute(globals.fs.path.normalize(outputArgument))); aotBuilder ??= AotBuilder(); bundleBuilder ??= BundleBuilder(); - cache ??= Cache.instance; + cache ??= globals.cache; for (BuildMode mode in buildModes) { - printStatus('Building framework for $iosProject in ${getNameForBuildMode(mode)} mode...'); + globals.printStatus('Building framework for $iosProject in ${getNameForBuildMode(mode)} mode...'); final String xcodeBuildConfiguration = toTitleCase(getNameForBuildMode(mode)); final Directory modeDirectory = outputDirectory.childDirectory(xcodeBuildConfiguration); @@ -188,7 +187,8 @@ await _producePlugins(mode, xcodeBuildConfiguration, iPhoneBuildOutput, simulatorBuildOutput, modeDirectory, outputDirectory); } - final Status status = logger.startProgress(' └─Moving to ${fs.path.relative(modeDirectory.path)}', timeout: timeoutConfiguration.slowOperation); + final Status status = globals.logger.startProgress( + ' └─Moving to ${globals.fs.path.relative(modeDirectory.path)}', timeout: timeoutConfiguration.slowOperation); try { // Delete the intermediaries since they would have been copied into our // output frameworks. @@ -203,7 +203,7 @@ } } - printStatus('Frameworks written to ${outputDirectory.path}.'); + globals.printStatus('Frameworks written to ${outputDirectory.path}.'); return null; } @@ -212,7 +212,7 @@ /// vendored framework caching. @visibleForTesting void produceFlutterPodspec(BuildMode mode, Directory modeDirectory) { - final Status status = logger.startProgress(' ├─Creating Flutter.podspec...', timeout: timeoutConfiguration.fastOperation); + final Status status = globals.logger.startProgress(' ├─Creating Flutter.podspec...', timeout: timeoutConfiguration.fastOperation); try { final GitTagVersion gitTagVersion = flutterVersion.gitTagVersion; if (gitTagVersion.x == null || gitTagVersion.y == null || gitTagVersion.z == null || gitTagVersion.commits != 0) { @@ -267,14 +267,14 @@ } Future<void> _produceFlutterFramework(Directory outputDirectory, BuildMode mode, Directory iPhoneBuildOutput, Directory simulatorBuildOutput, Directory modeDirectory) async { - final Status status = logger.startProgress(' ├─Populating Flutter.framework...', timeout: timeoutConfiguration.slowOperation); - final String engineCacheFlutterFrameworkDirectory = artifacts.getArtifactPath(Artifact.flutterFramework, platform: TargetPlatform.ios, mode: mode); - final String flutterFrameworkFileName = fs.path.basename(engineCacheFlutterFrameworkDirectory); + final Status status = globals.logger.startProgress(' ├─Populating Flutter.framework...', timeout: timeoutConfiguration.slowOperation); + final String engineCacheFlutterFrameworkDirectory = globals.artifacts.getArtifactPath(Artifact.flutterFramework, platform: TargetPlatform.ios, mode: mode); + final String flutterFrameworkFileName = globals.fs.path.basename(engineCacheFlutterFrameworkDirectory); final Directory fatFlutterFrameworkCopy = modeDirectory.childDirectory(flutterFrameworkFileName); try { // Copy universal engine cache framework to mode directory. - copyDirectorySync(fs.directory(engineCacheFlutterFrameworkDirectory), fatFlutterFrameworkCopy); + copyDirectorySync(globals.fs.directory(engineCacheFlutterFrameworkDirectory), fatFlutterFrameworkCopy); if (mode != BuildMode.debug) { final File fatFlutterFrameworkBinary = fatFlutterFrameworkCopy.childFile('Flutter'); @@ -312,7 +312,7 @@ destinationAppFrameworkDirectory.createSync(recursive: true); if (mode == BuildMode.debug) { - final Status status = logger.startProgress(' ├─Adding placeholder App.framework for debug...', timeout: timeoutConfiguration.fastOperation); + final Status status = globals.logger.startProgress(' ├─Adding placeholder App.framework for debug...', timeout: timeoutConfiguration.fastOperation); try { await _produceStubAppFrameworkIfNeeded(mode, iPhoneBuildOutput, simulatorBuildOutput, destinationAppFrameworkDirectory); } finally { @@ -327,13 +327,14 @@ destinationInfoPlist.writeAsBytesSync(sourceInfoPlist.readAsBytesSync()); - final Status status = logger.startProgress(' ├─Assembling Flutter resources for App.framework...', timeout: timeoutConfiguration.slowOperation); + final Status status = globals.logger.startProgress( + ' ├─Assembling Flutter resources for App.framework...', timeout: timeoutConfiguration.slowOperation); try { await bundleBuilder.build( platform: TargetPlatform.ios, buildMode: mode, // Relative paths show noise in the compiler https://github.com/dart-lang/sdk/issues/37978. - mainPath: fs.path.absolute(targetFile), + mainPath: globals.fs.path.absolute(targetFile), assetDirPath: destinationAppFrameworkDirectory.childDirectory('flutter_assets').path, precompiledSnapshot: mode != BuildMode.debug, ); @@ -382,14 +383,15 @@ if (mode == BuildMode.debug) { return; } - final Status status = logger.startProgress(' ├─Building Dart AOT for App.framework...', timeout: timeoutConfiguration.slowOperation); + final Status status = globals.logger.startProgress( + ' ├─Building Dart AOT for App.framework...', timeout: timeoutConfiguration.slowOperation); try { await aotBuilder.build( platform: TargetPlatform.ios, outputPath: iPhoneBuildOutput.path, buildMode: mode, // Relative paths show noise in the compiler https://github.com/dart-lang/sdk/issues/37978. - mainDartFile: fs.path.absolute(targetFile), + mainDartFile: globals.fs.path.absolute(targetFile), quiet: true, bitcode: true, reportTimings: false, @@ -412,7 +414,8 @@ Directory modeDirectory, Directory outputDirectory, ) async { - final Status status = logger.startProgress(' ├─Building plugins...', timeout: timeoutConfiguration.slowOperation); + final Status status = globals.logger.startProgress( + ' ├─Building plugins...', timeout: timeoutConfiguration.slowOperation); try { List<String> pluginsBuildCommand = <String>[ 'xcrun', @@ -470,15 +473,15 @@ for (Directory builtProduct in iPhoneBuildConfiguration.listSync(followLinks: false).whereType<Directory>()) { for (FileSystemEntity podProduct in builtProduct.listSync(followLinks: false)) { final String podFrameworkName = podProduct.basename; - if (fs.path.extension(podFrameworkName) == '.framework') { - final String binaryName = fs.path.basenameWithoutExtension(podFrameworkName); + if (globals.fs.path.extension(podFrameworkName) == '.framework') { + final String binaryName = globals.fs.path.basenameWithoutExtension(podFrameworkName); if (boolArg('universal')) { copyDirectorySync(podProduct as Directory, modeDirectory.childDirectory(podFrameworkName)); final List<String> lipoCommand = <String>[ 'xcrun', 'lipo', '-create', - fs.path.join(podProduct.path, binaryName), + globals.fs.path.join(podProduct.path, binaryName), if (mode == BuildMode.debug) simulatorBuildConfiguration.childDirectory(binaryName).childDirectory(podFrameworkName).childFile(binaryName).path, '-output', @@ -531,10 +534,10 @@ void _produceXCFramework(BuildMode mode, Directory fatFramework) { if (boolArg('xcframework')) { - final String frameworkBinaryName = fs.path.basenameWithoutExtension( + final String frameworkBinaryName = globals.fs.path.basenameWithoutExtension( fatFramework.basename); - final Status status = logger.startProgress(' ├─Creating $frameworkBinaryName.xcframework...', timeout: timeoutConfiguration.fastOperation); + final Status status = globals.logger.startProgress(' ├─Creating $frameworkBinaryName.xcframework...', timeout: timeoutConfiguration.fastOperation); try { if (mode == BuildMode.debug) { _produceDebugXCFramework(fatFramework, frameworkBinaryName); @@ -555,7 +558,7 @@ final String frameworkFileName = fatFramework.basename; final File fatFlutterFrameworkBinary = fatFramework.childFile( frameworkBinaryName); - final Directory temporaryOutput = fs.systemTempDirectory.createTempSync( + final Directory temporaryOutput = globals.fs.systemTempDirectory.createTempSync( 'flutter_tool_build_ios_framework.'); try { // Copy universal framework to variant directory.
diff --git a/packages/flutter_tools/lib/src/commands/build_linux.dart b/packages/flutter_tools/lib/src/commands/build_linux.dart index eb2d447..b3e9b78 100644 --- a/packages/flutter_tools/lib/src/commands/build_linux.dart +++ b/packages/flutter_tools/lib/src/commands/build_linux.dart
@@ -5,10 +5,10 @@ import 'dart:async'; import '../base/common.dart'; -import '../base/platform.dart'; import '../build_info.dart'; import '../cache.dart'; import '../features.dart'; +import '../globals.dart' as globals; import '../linux/build_linux.dart'; import '../project.dart'; import '../runner/flutter_command.dart' show FlutterCommandResult; @@ -25,7 +25,7 @@ final String name = 'linux'; @override - bool get hidden => !featureFlags.isLinuxEnabled || !platform.isLinux; + bool get hidden => !featureFlags.isLinuxEnabled || !globals.platform.isLinux; @override Future<Set<DevelopmentArtifact>> get requiredArtifacts async => <DevelopmentArtifact>{ @@ -43,7 +43,7 @@ if (!featureFlags.isLinuxEnabled) { throwToolExit('"build linux" is not currently supported.'); } - if (!platform.isLinux) { + if (!globals.platform.isLinux) { throwToolExit('"build linux" only supported on Linux hosts.'); } if (!flutterProject.linux.existsSync()) {
diff --git a/packages/flutter_tools/lib/src/commands/build_macos.dart b/packages/flutter_tools/lib/src/commands/build_macos.dart index 8ee6c45..c966f3c 100644 --- a/packages/flutter_tools/lib/src/commands/build_macos.dart +++ b/packages/flutter_tools/lib/src/commands/build_macos.dart
@@ -5,10 +5,10 @@ import 'dart:async'; import '../base/common.dart'; -import '../base/platform.dart'; import '../build_info.dart'; import '../cache.dart'; import '../features.dart'; +import '../globals.dart' as globals; import '../macos/build_macos.dart'; import '../project.dart'; import '../runner/flutter_command.dart' show FlutterCommandResult; @@ -25,7 +25,7 @@ final String name = 'macos'; @override - bool get hidden => !featureFlags.isMacOSEnabled || !platform.isMacOS; + bool get hidden => !featureFlags.isMacOSEnabled || !globals.platform.isMacOS; @override Future<Set<DevelopmentArtifact>> get requiredArtifacts async => <DevelopmentArtifact>{ @@ -43,7 +43,7 @@ if (!featureFlags.isMacOSEnabled) { throwToolExit('"build macos" is not currently supported.'); } - if (!platform.isMacOS) { + if (!globals.platform.isMacOS) { throwToolExit('"build macos" only supported on macOS hosts.'); } if (!flutterProject.macos.existsSync()) {
diff --git a/packages/flutter_tools/lib/src/commands/build_windows.dart b/packages/flutter_tools/lib/src/commands/build_windows.dart index 24d154d..7be232b 100644 --- a/packages/flutter_tools/lib/src/commands/build_windows.dart +++ b/packages/flutter_tools/lib/src/commands/build_windows.dart
@@ -5,10 +5,10 @@ import 'dart:async'; import '../base/common.dart'; -import '../base/platform.dart'; import '../build_info.dart'; import '../cache.dart'; import '../features.dart'; +import '../globals.dart' as globals; import '../project.dart'; import '../runner/flutter_command.dart' show FlutterCommandResult; import '../windows/build_windows.dart'; @@ -25,7 +25,7 @@ final String name = 'windows'; @override - bool get hidden => !featureFlags.isWindowsEnabled || !platform.isWindows; + bool get hidden => !featureFlags.isWindowsEnabled || !globals.platform.isWindows; @override Future<Set<DevelopmentArtifact>> get requiredArtifacts async => <DevelopmentArtifact>{ @@ -43,7 +43,7 @@ if (!featureFlags.isWindowsEnabled) { throwToolExit('"build windows" is not currently supported.'); } - if (!platform.isWindows) { + if (!globals.platform.isWindows) { throwToolExit('"build windows" only supported on Windows hosts.'); } if (!flutterProject.windows.existsSync()) {
diff --git a/packages/flutter_tools/lib/src/commands/channel.dart b/packages/flutter_tools/lib/src/commands/channel.dart index 2071d19..2b9461f 100644 --- a/packages/flutter_tools/lib/src/commands/channel.dart +++ b/packages/flutter_tools/lib/src/commands/channel.dart
@@ -7,7 +7,7 @@ import '../base/common.dart'; import '../base/process.dart'; import '../cache.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../runner/flutter_command.dart'; import '../version.dart'; @@ -60,7 +60,7 @@ showAll = showAll || currentChannel != currentBranch; - printStatus('Flutter channels:'); + globals.printStatus('Flutter channels:'); final int result = await processUtils.stream( <String>['git', 'branch', '-r'], workingDirectory: Cache.flutterRoot, @@ -94,12 +94,12 @@ } Future<void> _switchChannel(String branchName) { - printStatus("Switching to flutter channel '$branchName'..."); + globals.printStatus("Switching to flutter channel '$branchName'..."); if (FlutterVersion.obsoleteBranches.containsKey(branchName)) { final String alternative = FlutterVersion.obsoleteBranches[branchName]; - printStatus("This channel is obsolete. Consider switching to the '$alternative' channel instead."); + globals.printStatus("This channel is obsolete. Consider switching to the '$alternative' channel instead."); } else if (!FlutterVersion.officialChannels.contains(branchName)) { - printStatus('This is not an official channel. For a list of available channels, try "flutter channel".'); + globals.printStatus('This is not an official channel. For a list of available channels, try "flutter channel".'); } return _checkout(branchName); } @@ -108,7 +108,7 @@ final String channel = FlutterVersion.instance.channel; if (FlutterVersion.obsoleteBranches.containsKey(channel)) { final String alternative = FlutterVersion.obsoleteBranches[channel]; - printStatus("Transitioning from '$channel' to '$alternative'..."); + globals.printStatus("Transitioning from '$channel' to '$alternative'..."); return _checkout(alternative); } }
diff --git a/packages/flutter_tools/lib/src/commands/clean.dart b/packages/flutter_tools/lib/src/commands/clean.dart index f1b7140..5d7bc07 100644 --- a/packages/flutter_tools/lib/src/commands/clean.dart +++ b/packages/flutter_tools/lib/src/commands/clean.dart
@@ -8,9 +8,8 @@ import '../base/file_system.dart'; import '../base/logger.dart'; -import '../base/platform.dart'; import '../build_info.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../ios/xcodeproj.dart'; import '../macos/xcode.dart'; import '../project.dart'; @@ -40,7 +39,7 @@ await _cleanXcode(flutterProject.macos); } - final Directory buildDir = fs.directory(getBuildDirectory()); + final Directory buildDir = globals.fs.directory(getBuildDirectory()); deleteFile(buildDir); deleteFile(flutterProject.dartTool); @@ -67,7 +66,10 @@ if (!xcodeProject.existsSync()) { return; } - final Status xcodeStatus = logger.startProgress('Cleaning Xcode workspace...', timeout: timeoutConfiguration.slowOperation); + final Status xcodeStatus = globals.logger.startProgress( + 'Cleaning Xcode workspace...', + timeout: timeoutConfiguration.slowOperation, + ); try { final Directory xcodeWorkspace = xcodeProject.xcodeWorkspace; final XcodeProjectInfo projectInfo = await xcodeProjectInterpreter.getInfo(xcodeWorkspace.parent.path); @@ -75,7 +77,7 @@ xcodeProjectInterpreter.cleanWorkspace(xcodeWorkspace.path, scheme); } } catch (error) { - printTrace('Could not clean Xcode workspace: $error'); + globals.printTrace('Could not clean Xcode workspace: $error'); } finally { xcodeStatus?.stop(); } @@ -89,22 +91,25 @@ return; } } on FileSystemException catch (err) { - printError('Cannot clean ${file.path}.\n$err'); + globals.printError('Cannot clean ${file.path}.\n$err'); return; } - final Status deletionStatus = logger.startProgress('Deleting ${file.basename}...', timeout: timeoutConfiguration.fastOperation); + final Status deletionStatus = globals.logger.startProgress( + 'Deleting ${file.basename}...', + timeout: timeoutConfiguration.fastOperation, + ); try { file.deleteSync(recursive: true); } on FileSystemException catch (error) { final String path = file.path; - if (platform.isWindows) { - printError( + if (globals.platform.isWindows) { + globals.printError( 'Failed to remove $path. ' 'A program may still be using a file in the directory or the directory itself. ' 'To find and stop such a program, see: ' 'https://superuser.com/questions/1333118/cant-delete-empty-folder-because-it-is-used'); } else { - printError('Failed to remove $path: $error'); + globals.printError('Failed to remove $path: $error'); } } finally { deletionStatus.stop();
diff --git a/packages/flutter_tools/lib/src/commands/config.dart b/packages/flutter_tools/lib/src/commands/config.dart index bbe6044..d1626ac 100644 --- a/packages/flutter_tools/lib/src/commands/config.dart +++ b/packages/flutter_tools/lib/src/commands/config.dart
@@ -7,10 +7,9 @@ import '../android/android_sdk.dart'; import '../android/android_studio.dart'; import '../base/common.dart'; -import '../base/file_system.dart'; import '../convert.dart'; import '../features.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../reporting/reporting.dart'; import '../runner/flutter_command.dart'; import '../version.dart'; @@ -75,7 +74,7 @@ featuresByName[feature.configSetting] = feature; } } - String values = config.keys + String values = globals.config.keys .map<String>((String key) { String configFooter = ''; if (featuresByName.containsKey(key)) { @@ -84,7 +83,7 @@ configFooter = '(Unavailable)'; } } - return ' $key: ${config.getValue(key)} $configFooter'; + return ' $key: ${globals.config.getValue(key)} $configFooter'; }).join('\n'); if (values.isEmpty) { values = ' No settings have been configured.'; @@ -108,7 +107,7 @@ if (boolArg('clear-features')) { for (Feature feature in allFeatures) { if (feature.configSetting != null) { - config.removeValue(feature.configSetting); + globals.config.removeValue(feature.configSetting); } } return null; @@ -118,7 +117,7 @@ final bool value = boolArg('analytics'); flutterUsage.enabled = value; AnalyticsConfigEvent(enabled: value).send(); - printStatus('Analytics reporting ${value ? 'enabled' : 'disabled'}.'); + globals.printStatus('Analytics reporting ${value ? 'enabled' : 'disabled'}.'); } if (argResults.wasParsed('android-sdk')) { @@ -135,7 +134,7 @@ if (argResults.wasParsed('build-dir')) { final String buildDir = stringArg('build-dir'); - if (fs.path.isAbsolute(buildDir)) { + if (globals.fs.path.isAbsolute(buildDir)) { throwToolExit('build-dir should be a relative path'); } _updateConfig('build-dir', buildDir); @@ -147,15 +146,15 @@ } if (argResults.wasParsed(feature.configSetting)) { final bool keyValue = boolArg(feature.configSetting); - config.setValue(feature.configSetting, keyValue); - printStatus('Setting "${feature.configSetting}" value to "$keyValue".'); + globals.config.setValue(feature.configSetting, keyValue); + globals.printStatus('Setting "${feature.configSetting}" value to "$keyValue".'); } } if (argResults.arguments.isEmpty) { - printStatus(usage); + globals.printStatus(usage); } else { - printStatus('\nYou may need to restart any open editors for them to read new settings.'); + globals.printStatus('\nYou may need to restart any open editors for them to read new settings.'); } return null; @@ -164,8 +163,8 @@ Future<void> handleMachine() async { // Get all the current values. final Map<String, dynamic> results = <String, dynamic>{}; - for (String key in config.keys) { - results[key] = config.getValue(key); + for (String key in globals.config.keys) { + results[key] = globals.config.getValue(key); } // Ensure we send any calculated ones, if overrides don't exist. @@ -176,16 +175,16 @@ results['android-sdk'] = androidSdk.directory; } - printStatus(const JsonEncoder.withIndent(' ').convert(results)); + globals.printStatus(const JsonEncoder.withIndent(' ').convert(results)); } void _updateConfig(String keyName, String keyValue) { if (keyValue.isEmpty) { - config.removeValue(keyName); - printStatus('Removing "$keyName" value.'); + globals.config.removeValue(keyName); + globals.printStatus('Removing "$keyName" value.'); } else { - config.setValue(keyName, keyValue); - printStatus('Setting "$keyName" value to "$keyValue".'); + globals.config.setValue(keyName, keyValue); + globals.printStatus('Setting "$keyName" value to "$keyValue".'); } } }
diff --git a/packages/flutter_tools/lib/src/commands/create.dart b/packages/flutter_tools/lib/src/commands/create.dart index 071d4a7..823da6a 100644 --- a/packages/flutter_tools/lib/src/commands/create.dart +++ b/packages/flutter_tools/lib/src/commands/create.dart
@@ -20,7 +20,7 @@ import '../dart/pub.dart'; import '../doctor.dart'; import '../features.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../project.dart'; import '../reporting/reporting.dart'; import '../runner/flutter_command.dart'; @@ -176,7 +176,7 @@ if (!projectDir.existsSync()) { return null; } - final File metadataFile = fs.file(fs.path.join(projectDir.absolute.path, '.metadata')); + final File metadataFile = globals.fs.file(globals.fs.path.join(projectDir.absolute.path, '.metadata')); if (!metadataFile.existsSync()) { return null; } @@ -190,7 +190,7 @@ } bool exists(List<String> path) { - return fs.directory(fs.path.joinAll(<String>[projectDir.absolute.path, ...path])).existsSync(); + return globals.fs.directory(globals.fs.path.joinAll(<String>[projectDir.absolute.path, ...path])).existsSync(); } // If it exists, the project type in the metadata is definitive. @@ -243,7 +243,7 @@ /// [outputFilePath]. Future<void> _writeSamplesJson(String outputFilePath) async { try { - final File outputFile = fs.file(outputFilePath); + final File outputFile = globals.fs.file(outputFilePath); if (outputFile.existsSync()) { throwToolExit('File "$outputFilePath" already exists', exitCode: 1); } @@ -253,7 +253,7 @@ } else { outputFile.writeAsStringSync(samplesJson); - printStatus('Wrote samples JSON to "$outputFilePath"'); + globals.printStatus('Wrote samples JSON to "$outputFilePath"'); } } catch (e) { throwToolExit('Failed to write samples JSON to "$outputFilePath": $e', exitCode: 2); @@ -320,21 +320,21 @@ 'variable was specified. Unable to find package:flutter.', exitCode: 2); } - final String flutterRoot = fs.path.absolute(Cache.flutterRoot); + final String flutterRoot = globals.fs.path.absolute(Cache.flutterRoot); - final String flutterPackagesDirectory = fs.path.join(flutterRoot, 'packages'); - final String flutterPackagePath = fs.path.join(flutterPackagesDirectory, 'flutter'); - if (!fs.isFileSync(fs.path.join(flutterPackagePath, 'pubspec.yaml'))) { + final String flutterPackagesDirectory = globals.fs.path.join(flutterRoot, 'packages'); + final String flutterPackagePath = globals.fs.path.join(flutterPackagesDirectory, 'flutter'); + if (!globals.fs.isFileSync(globals.fs.path.join(flutterPackagePath, 'pubspec.yaml'))) { throwToolExit('Unable to find package:flutter in $flutterPackagePath', exitCode: 2); } - final String flutterDriverPackagePath = fs.path.join(flutterRoot, 'packages', 'flutter_driver'); - if (!fs.isFileSync(fs.path.join(flutterDriverPackagePath, 'pubspec.yaml'))) { + final String flutterDriverPackagePath = globals.fs.path.join(flutterRoot, 'packages', 'flutter_driver'); + if (!globals.fs.isFileSync(globals.fs.path.join(flutterDriverPackagePath, 'pubspec.yaml'))) { throwToolExit('Unable to find package:flutter_driver in $flutterDriverPackagePath', exitCode: 2); } - final Directory projectDir = fs.directory(argResults.rest.first); - final String projectDirPath = fs.path.normalize(projectDir.absolute.path); + final Directory projectDir = globals.fs.directory(argResults.rest.first); + final String projectDirPath = globals.fs.path.normalize(projectDir.absolute.path); String sampleCode; if (argResults['sample'] != null) { @@ -372,7 +372,7 @@ throwToolExit(error); } - final String projectName = stringArg('project-name') ?? fs.path.basename(projectDirPath); + final String projectName = stringArg('project-name') ?? globals.fs.path.basename(projectDirPath); error = _validateProjectName(projectName); if (error != null) { throwToolExit(error); @@ -392,18 +392,18 @@ macos: featureFlags.isMacOSEnabled, ); - final String relativeDirPath = fs.path.relative(projectDirPath); + final String relativeDirPath = globals.fs.path.relative(projectDirPath); if (!projectDir.existsSync() || projectDir.listSync().isEmpty) { - printStatus('Creating project $relativeDirPath... androidx: ${boolArg('androidx')}'); + globals.printStatus('Creating project $relativeDirPath... androidx: ${boolArg('androidx')}'); } else { if (sampleCode != null && !overwrite) { throwToolExit('Will not overwrite existing project in $relativeDirPath: ' 'must specify --overwrite for samples to overwrite.'); } - printStatus('Recreating project $relativeDirPath...'); + globals.printStatus('Recreating project $relativeDirPath...'); } - final Directory relativeDir = fs.directory(projectDirPath); + final Directory relativeDir = globals.fs.directory(projectDirPath); int generatedFileCount = 0; switch (template) { case _ProjectType.app: @@ -422,36 +422,36 @@ if (sampleCode != null) { generatedFileCount += _applySample(relativeDir, sampleCode); } - printStatus('Wrote $generatedFileCount files.'); - printStatus('\nAll done!'); + globals.printStatus('Wrote $generatedFileCount files.'); + globals.printStatus('\nAll done!'); final String application = sampleCode != null ? 'sample application' : 'application'; if (generatePackage) { - final String relativeMainPath = fs.path.normalize(fs.path.join( + final String relativeMainPath = globals.fs.path.normalize(globals.fs.path.join( relativeDirPath, 'lib', '${templateContext['projectName']}.dart', )); - printStatus('Your package code is in $relativeMainPath'); + globals.printStatus('Your package code is in $relativeMainPath'); } else if (generateModule) { - final String relativeMainPath = fs.path.normalize(fs.path.join( + final String relativeMainPath = globals.fs.path.normalize(globals.fs.path.join( relativeDirPath, 'lib', 'main.dart', )); - printStatus('Your module code is in $relativeMainPath.'); + globals.printStatus('Your module code is in $relativeMainPath.'); } else { // Run doctor; tell the user the next steps. final FlutterProject project = FlutterProject.fromPath(projectDirPath); final FlutterProject app = project.hasExampleApp ? project.example : project; - final String relativeAppPath = fs.path.normalize(fs.path.relative(app.directory.path)); - final String relativeAppMain = fs.path.join(relativeAppPath, 'lib', 'main.dart'); - final String relativePluginPath = fs.path.normalize(fs.path.relative(projectDirPath)); - final String relativePluginMain = fs.path.join(relativePluginPath, 'lib', '$projectName.dart'); + final String relativeAppPath = globals.fs.path.normalize(globals.fs.path.relative(app.directory.path)); + final String relativeAppMain = globals.fs.path.join(relativeAppPath, 'lib', 'main.dart'); + final String relativePluginPath = globals.fs.path.normalize(globals.fs.path.relative(projectDirPath)); + final String relativePluginMain = globals.fs.path.join(relativePluginPath, 'lib', '$projectName.dart'); if (doctor.canLaunchAnything) { // Let them know a summary of the state of their tooling. await doctor.summary(); - printStatus(''' + globals.printStatus(''' In order to run your $application, type: \$ cd $relativeAppPath @@ -460,7 +460,7 @@ Your $application code is in $relativeAppMain. '''); if (generatePlugin) { - printStatus(''' + globals.printStatus(''' Your plugin code is in $relativePluginMain. Host platform code is in the "android" and "ios" directories under $relativePluginPath. @@ -468,18 +468,18 @@ '''); } } else { - printStatus("You'll need to install additional components before you can run " + globals.printStatus("You'll need to install additional components before you can run " 'your Flutter app:'); - printStatus(''); + globals.printStatus(''); // Give the user more detailed analysis. await doctor.diagnose(); - printStatus(''); - printStatus("After installing components, run 'flutter doctor' in order to " + globals.printStatus(''); + globals.printStatus("After installing components, run 'flutter doctor' in order to " 're-validate your setup.'); - printStatus("When complete, type 'flutter run' from the '$relativeAppPath' " + globals.printStatus("When complete, type 'flutter run' from the '$relativeAppPath' " 'directory in order to launch your app.'); - printStatus('Your $application code is in $relativeAppMain'); + globals.printStatus('Your $application code is in $relativeAppMain'); } } @@ -492,7 +492,7 @@ ? stringArg('description') : 'A new flutter module project.'; templateContext['description'] = description; - generatedCount += _renderTemplate(fs.path.join('module', 'common'), directory, templateContext, overwrite: overwrite); + generatedCount += _renderTemplate(globals.fs.path.join('module', 'common'), directory, templateContext, overwrite: overwrite); if (boolArg('pub')) { await pub.get( context: PubContext.create, @@ -602,7 +602,7 @@ bool web = false, bool macos = false, }) { - flutterRoot = fs.path.normalize(flutterRoot); + flutterRoot = globals.fs.path.normalize(flutterRoot); final String pluginDartClass = _createPluginClassName(projectName); final String pluginClass = pluginDartClass.endsWith('Plugin') @@ -652,7 +652,7 @@ int _injectGradleWrapper(FlutterProject project) { int filesCreated = 0; copyDirectorySync( - cache.getArtifactDirectory('gradle_wrapper'), + globals.cache.getArtifactDirectory('gradle_wrapper'), project.android.hostAppGradleRoot, onFileCopied: (File sourceFile, File destinationFile) { filesCreated++; @@ -850,14 +850,14 @@ /// Return null if the project directory is legal. Return a validation message /// if we should disallow the directory name. String _validateProjectDir(String dirPath, { String flutterRoot, bool overwrite = false }) { - if (fs.path.isWithin(flutterRoot, dirPath)) { + if (globals.fs.path.isWithin(flutterRoot, dirPath)) { return 'Cannot create a project within the Flutter SDK. ' "Target directory '$dirPath' is within the Flutter SDK at '$flutterRoot'."; } // If the destination directory is actually a file, then we refuse to // overwrite, on the theory that the user probably didn't expect it to exist. - if (fs.isFileSync(dirPath)) { + if (globals.fs.isFileSync(dirPath)) { return "Invalid project name: '$dirPath' - refers to an existing file." '${overwrite ? ' Refusing to overwrite a file with a directory.' : ''}'; } @@ -866,7 +866,7 @@ return null; } - final FileSystemEntityType type = fs.typeSync(dirPath); + final FileSystemEntityType type = globals.fs.typeSync(dirPath); if (type != FileSystemEntityType.notFound) { switch (type) {
diff --git a/packages/flutter_tools/lib/src/commands/daemon.dart b/packages/flutter_tools/lib/src/commands/daemon.dart index d4dd562..0c30d60 100644 --- a/packages/flutter_tools/lib/src/commands/daemon.dart +++ b/packages/flutter_tools/lib/src/commands/daemon.dart
@@ -18,7 +18,7 @@ import '../convert.dart'; import '../device.dart'; import '../emulator.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../project.dart'; import '../resident_runner.dart'; import '../run_cold.dart'; @@ -50,7 +50,7 @@ @override Future<FlutterCommandResult> runCommand() async { - printStatus('Starting device daemon...'); + globals.printStatus('Starting device daemon...'); isRunningFromDaemon = true; final NotifyingLogger notifyingLogger = NotifyingLogger(); @@ -361,7 +361,7 @@ if (res is Map<String, dynamic> && res['url'] is String) { return res['url'] as String; } else { - printError('Invalid response to exposeUrl - params should include a String url field'); + globals.printError('Invalid response to exposeUrl - params should include a String url field'); return url; } } @@ -387,7 +387,7 @@ try { // TODO(jonahwilliams): replace this with a project metadata check once // that has been implemented. - final FlutterProject flutterProject = FlutterProject.fromDirectory(fs.directory(projectRoot)); + final FlutterProject flutterProject = FlutterProject.fromDirectory(globals.fs.directory(projectRoot)); if (flutterProject.linux.existsSync()) { result.add('linux'); } @@ -472,8 +472,8 @@ throw '${toTitleCase(options.buildInfo.friendlyModeName)} mode is not supported for emulators.'; } // We change the current working directory for the duration of the `start` command. - final Directory cwd = fs.currentDirectory; - fs.currentDirectory = fs.directory(projectDirectory); + final Directory cwd = globals.fs.currentDirectory; + globals.fs.currentDirectory = globals.fs.directory(projectDirectory); final FlutterProject flutterProject = FlutterProject.current(); final FlutterDevice flutterDevice = await FlutterDevice.create( @@ -600,7 +600,7 @@ 'trace': '$trace', }); } finally { - fs.currentDirectory = cwd; + globals.fs.currentDirectory = cwd; _apps.remove(app); } }); @@ -779,7 +779,7 @@ final Map<String, Object> response = await _deviceToMap(device); sendEvent(eventName, response); } catch (err) { - printError('$err'); + globals.printError('$err'); } }); }; @@ -1011,7 +1011,7 @@ } Future<T> _runInZone<T>(AppDomain domain, FutureOr<T> method()) { - _logger ??= _AppRunLogger(domain, this, parent: logToStdout ? logger : null); + _logger ??= _AppRunLogger(domain, this, parent: logToStdout ? globals.logger : null); return context.run<T>( body: method,
diff --git a/packages/flutter_tools/lib/src/commands/devices.dart b/packages/flutter_tools/lib/src/commands/devices.dart index b9842f5..dbae667 100644 --- a/packages/flutter_tools/lib/src/commands/devices.dart +++ b/packages/flutter_tools/lib/src/commands/devices.dart
@@ -8,7 +8,7 @@ import '../base/utils.dart'; import '../device.dart'; import '../doctor.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../runner/flutter_command.dart'; class DevicesCommand extends FlutterCommand { @@ -30,20 +30,20 @@ final List<Device> devices = await deviceManager.getAllConnectedDevices().toList(); if (devices.isEmpty) { - printStatus( + globals.printStatus( 'No devices detected.\n\n' "Run 'flutter emulators' to list and start any available device emulators.\n\n" 'Or, if you expected your device to be detected, please run "flutter doctor" to diagnose ' 'potential issues, or visit https://flutter.dev/setup/ for troubleshooting tips.'); final List<String> diagnostics = await deviceManager.getDeviceDiagnostics(); if (diagnostics.isNotEmpty) { - printStatus(''); + globals.printStatus(''); for (String diagnostic in diagnostics) { - printStatus('• $diagnostic', hangingIndent: 2); + globals.printStatus('• $diagnostic', hangingIndent: 2); } } } else { - printStatus('${devices.length} connected ${pluralize('device', devices.length)}:\n'); + globals.printStatus('${devices.length} connected ${pluralize('device', devices.length)}:\n'); await Device.printDevices(devices); }
diff --git a/packages/flutter_tools/lib/src/commands/drive.dart b/packages/flutter_tools/lib/src/commands/drive.dart index 5245c61..c69fe0b 100644 --- a/packages/flutter_tools/lib/src/commands/drive.dart +++ b/packages/flutter_tools/lib/src/commands/drive.dart
@@ -12,7 +12,7 @@ import '../dart/package_map.dart'; import '../dart/sdk.dart'; import '../device.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../project.dart'; import '../resident_runner.dart'; import '../runner/flutter_command.dart' show FlutterCommandResult; @@ -131,13 +131,13 @@ throwToolExit(null); } - if (await fs.type(testFile) != FileSystemEntityType.file) { + if (await globals.fs.type(testFile) != FileSystemEntityType.file) { throwToolExit('Test file not found: $testFile'); } String observatoryUri; if (argResults['use-existing-app'] == null) { - printStatus('Starting application: $targetFile'); + globals.printStatus('Starting application: $targetFile'); if (getBuildInfo().isRelease) { // This is because we need VM service to be able to drive the app. @@ -155,7 +155,7 @@ } observatoryUri = result.observatoryUri.toString(); } else { - printStatus('Will connect to already running application instance.'); + globals.printStatus('Will connect to already running application instance.'); observatoryUri = stringArg('use-existing-app'); } @@ -178,9 +178,9 @@ throwToolExit('CAUGHT EXCEPTION: $error\n$stackTrace'); } finally { if (boolArg('keep-app-running') ?? (argResults['use-existing-app'] != null)) { - printStatus('Leaving the application running.'); + globals.printStatus('Leaving the application running.'); } else { - printStatus('Stopping application instance.'); + globals.printStatus('Stopping application instance.'); await appStopper(this); } } @@ -195,28 +195,28 @@ // If the --driver argument wasn't provided, then derive the value from // the target file. - String appFile = fs.path.normalize(targetFile); + String appFile = globals.fs.path.normalize(targetFile); // This command extends `flutter run` and therefore CWD == package dir - final String packageDir = fs.currentDirectory.path; + final String packageDir = globals.fs.currentDirectory.path; // Make appFile path relative to package directory because we are looking // for the corresponding test file relative to it. - if (!fs.path.isRelative(appFile)) { - if (!fs.path.isWithin(packageDir, appFile)) { - printError( + if (!globals.fs.path.isRelative(appFile)) { + if (!globals.fs.path.isWithin(packageDir, appFile)) { + globals.printError( 'Application file $appFile is outside the package directory $packageDir' ); return null; } - appFile = fs.path.relative(appFile, from: packageDir); + appFile = globals.fs.path.relative(appFile, from: packageDir); } - final List<String> parts = fs.path.split(appFile); + final List<String> parts = globals.fs.path.split(appFile); if (parts.length < 2) { - printError( + globals.printError( 'Application file $appFile must reside in one of the sub-directories ' 'of the package structure, not in the root directory.' ); @@ -226,9 +226,9 @@ // Look for the test file inside `test_driver/` matching the sub-path, e.g. // if the application is `lib/foo/bar.dart`, the test file is expected to // be `test_driver/foo/bar_test.dart`. - final String pathWithNoExtension = fs.path.withoutExtension(fs.path.joinAll( + final String pathWithNoExtension = globals.fs.path.withoutExtension(globals.fs.path.joinAll( <String>[packageDir, 'test_driver', ...parts.skip(1)])); - return '${pathWithNoExtension}_test${fs.path.extension(appFile)}'; + return '${pathWithNoExtension}_test${globals.fs.path.extension(appFile)}'; } } @@ -237,11 +237,11 @@ if (deviceManager.hasSpecifiedDeviceId) { if (devices.isEmpty) { - printStatus("No devices found with name or id matching '${deviceManager.specifiedDeviceId}'"); + globals.printStatus("No devices found with name or id matching '${deviceManager.specifiedDeviceId}'"); return null; } if (devices.length > 1) { - printStatus("Found ${devices.length} devices with name or id matching '${deviceManager.specifiedDeviceId}':"); + globals.printStatus("Found ${devices.length} devices with name or id matching '${deviceManager.specifiedDeviceId}':"); await Device.printDevices(devices); return null; } @@ -249,13 +249,13 @@ } if (devices.isEmpty) { - printError('No devices found.'); + globals.printError('No devices found.'); return null; } else if (devices.length > 1) { - printStatus('Found multiple connected devices:'); + globals.printStatus('Found multiple connected devices:'); await Device.printDevices(devices); } - printStatus('Using device ${devices.first.name}.'); + globals.printStatus('Using device ${devices.first.name}.'); return devices.first; } @@ -269,19 +269,19 @@ Future<LaunchResult> _startApp(DriveCommand command) async { final String mainPath = findMainDartFile(command.targetFile); - if (await fs.type(mainPath) != FileSystemEntityType.file) { - printError('Tried to run $mainPath, but that file does not exist.'); + if (await globals.fs.type(mainPath) != FileSystemEntityType.file) { + globals.printError('Tried to run $mainPath, but that file does not exist.'); return null; } - printTrace('Stopping previously running application, if any.'); + globals.printTrace('Stopping previously running application, if any.'); await appStopper(command); final ApplicationPackage package = await command.applicationPackages .getPackageForPlatform(await command.device.targetPlatform); if (command.shouldBuild) { - printTrace('Installing application package.'); + globals.printTrace('Installing application package.'); if (await command.device.isAppInstalled(package)) { await command.device.uninstallApp(package); } @@ -293,14 +293,14 @@ platformArgs['trace-startup'] = command.traceStartup; } - printTrace('Starting application.'); + globals.printTrace('Starting application.'); // Forward device log messages to the terminal window running the "drive" command. command._deviceLogSubscription = command .device .getLogReader(app: package) .logLines - .listen(printStatus); + .listen(globals.printStatus); final LaunchResult result = await command.device.startApp( package, @@ -334,10 +334,10 @@ } Future<void> _runTests(List<String> testArgs, Map<String, String> environment) async { - printTrace('Running driver tests.'); + globals.printTrace('Running driver tests.'); - PackageMap.globalPackagesPath = fs.path.normalize(fs.path.absolute(PackageMap.globalPackagesPath)); - final String dartVmPath = fs.path.join(dartSdkPath, 'bin', 'dart'); + PackageMap.globalPackagesPath = globals.fs.path.normalize(globals.fs.path.absolute(PackageMap.globalPackagesPath)); + final String dartVmPath = globals.fs.path.join(dartSdkPath, 'bin', 'dart'); final int result = await processUtils.stream( <String>[ dartVmPath, @@ -362,7 +362,7 @@ } Future<bool> _stopApp(DriveCommand command) async { - printTrace('Stopping application.'); + globals.printTrace('Stopping application.'); final ApplicationPackage package = await command.applicationPackages.getPackageForPlatform(await command.device.targetPlatform); final bool stopped = await command.device.stopApp(package); await command._deviceLogSubscription?.cancel();
diff --git a/packages/flutter_tools/lib/src/commands/emulators.dart b/packages/flutter_tools/lib/src/commands/emulators.dart index ae84aec..320884d 100644 --- a/packages/flutter_tools/lib/src/commands/emulators.dart +++ b/packages/flutter_tools/lib/src/commands/emulators.dart
@@ -5,11 +5,10 @@ import 'dart:async'; import '../base/common.dart'; -import '../base/platform.dart'; import '../base/utils.dart'; import '../doctor.dart'; import '../emulator.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../runner/flutter_command.dart'; class EmulatorsCommand extends FlutterCommand { @@ -38,7 +37,7 @@ throwToolExit( 'Unable to find any emulator sources. Please ensure you have some\n' 'Android AVD images ' + - (platform.isMacOS ? 'or an iOS Simulator ' : '') + + (globals.platform.isMacOS ? 'or an iOS Simulator ' : '') + 'available.', exitCode: 1); } @@ -63,7 +62,7 @@ await emulatorManager.getEmulatorsMatching(id); if (emulators.isEmpty) { - printStatus("No emulator found that matches '$id'."); + globals.printStatus("No emulator found that matches '$id'."); } else if (emulators.length > 1) { _printEmulatorList( emulators, @@ -75,7 +74,7 @@ } catch (e) { if (e is String) { - printError(e); + globals.printError(e); } else { rethrow; } @@ -88,10 +87,10 @@ await emulatorManager.createEmulator(name: name); if (createResult.success) { - printStatus("Emulator '${createResult.emulatorName}' created successfully."); + globals.printStatus("Emulator '${createResult.emulatorName}' created successfully."); } else { - printStatus("Failed to create emulator '${createResult.emulatorName}'.\n"); - printStatus(createResult.error.trim()); + globals.printStatus("Failed to create emulator '${createResult.emulatorName}'.\n"); + globals.printStatus(createResult.error.trim()); _printAdditionalInfo(); } } @@ -102,7 +101,7 @@ : await emulatorManager.getEmulatorsMatching(searchText); if (emulators.isEmpty) { - printStatus('No emulators available.'); + globals.printStatus('No emulators available.'); _printAdditionalInfo(showCreateInstruction: true); } else { _printEmulatorList( @@ -113,7 +112,7 @@ } void _printEmulatorList(List<Emulator> emulators, String message) { - printStatus('$message\n'); + globals.printStatus('$message\n'); Emulator.printEmulators(emulators); _printAdditionalInfo(showCreateInstruction: true, showRunInstruction: true); } @@ -122,22 +121,22 @@ bool showRunInstruction = false, bool showCreateInstruction = false, }) { - printStatus(''); + globals.printStatus(''); if (showRunInstruction) { - printStatus( + globals.printStatus( "To run an emulator, run 'flutter emulators --launch <emulator id>'."); } if (showCreateInstruction) { - printStatus( + globals.printStatus( "To create a new emulator, run 'flutter emulators --create [--name xyz]'."); } if (showRunInstruction || showCreateInstruction) { - printStatus(''); + globals.printStatus(''); } // TODO(dantup): Update this link to flutter.dev if/when we have a better page. // That page can then link out to these places if required. - printStatus('You can find more information on managing emulators at the links below:\n' + globals.printStatus('You can find more information on managing emulators at the links below:\n' ' https://developer.android.com/studio/run/managing-avds\n' ' https://developer.android.com/studio/command-line/avdmanager'); }
diff --git a/packages/flutter_tools/lib/src/commands/generate.dart b/packages/flutter_tools/lib/src/commands/generate.dart index 5cf4fb3..7b23bae 100644 --- a/packages/flutter_tools/lib/src/commands/generate.dart +++ b/packages/flutter_tools/lib/src/commands/generate.dart
@@ -6,7 +6,7 @@ import '../cache.dart'; import '../codegen.dart'; import '../convert.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../project.dart'; import '../runner/flutter_command.dart'; @@ -28,7 +28,7 @@ codegenDaemon.startBuild(); await for (CodegenStatus codegenStatus in codegenDaemon.buildResults) { if (codegenStatus == CodegenStatus.Failed) { - printError('Code generation failed.'); + globals.printError('Code generation failed.'); break; } if (codegenStatus ==CodegenStatus.Succeeded) { @@ -48,12 +48,12 @@ try { final List<Object> errorData = json.decode(errorFile.readAsStringSync()) as List<Object>; final List<Object> stackData = errorData[1] as List<Object>; - printError(errorData.first as String); - printError(stackData[0] as String); - printError(stackData[1] as String); - printError(StackTrace.fromString(stackData[2] as String).toString()); + globals.printError(errorData.first as String); + globals.printError(stackData[0] as String); + globals.printError(stackData[1] as String); + globals.printError(StackTrace.fromString(stackData[2] as String).toString()); } catch (err) { - printError('Error reading error in ${errorFile.path}'); + globals.printError('Error reading error in ${errorFile.path}'); } } return const FlutterCommandResult(ExitStatus.fail);
diff --git a/packages/flutter_tools/lib/src/commands/ide_config.dart b/packages/flutter_tools/lib/src/commands/ide_config.dart index e343c69..fd1c6fc 100644 --- a/packages/flutter_tools/lib/src/commands/ide_config.dart +++ b/packages/flutter_tools/lib/src/commands/ide_config.dart
@@ -7,7 +7,7 @@ import '../base/common.dart'; import '../base/file_system.dart'; import '../cache.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../runner/flutter_command.dart'; import '../template.dart'; @@ -64,7 +64,7 @@ static const String _ideName = 'intellij'; Directory get _templateDirectory { - return fs.directory(fs.path.join( + return globals.fs.directory(globals.fs.path.join( Cache.flutterRoot, 'packages', 'flutter_tools', @@ -74,7 +74,7 @@ } Directory get _createTemplatesDirectory { - return fs.directory(fs.path.join( + return globals.fs.directory(globals.fs.path.join( Cache.flutterRoot, 'packages', 'flutter_tools', @@ -82,16 +82,16 @@ )); } - Directory get _flutterRoot => fs.directory(fs.path.absolute(Cache.flutterRoot)); + Directory get _flutterRoot => globals.fs.directory(globals.fs.path.absolute(Cache.flutterRoot)); // Returns true if any entire path element is equal to dir. bool _hasDirectoryInPath(FileSystemEntity entity, String dir) { String path = entity.absolute.path; - while (path.isNotEmpty && fs.path.dirname(path) != path) { - if (fs.path.basename(path) == dir) { + while (path.isNotEmpty && globals.fs.path.dirname(path) != path) { + if (globals.fs.path.basename(path) == dir) { return true; } - path = fs.path.dirname(path); + path = globals.fs.path.dirname(path); } return false; } @@ -127,7 +127,7 @@ final Set<String> manifest = <String>{}; final Iterable<File> flutterFiles = _flutterRoot.listSync(recursive: true).whereType<File>(); for (File srcFile in flutterFiles) { - final String relativePath = fs.path.relative(srcFile.path, from: _flutterRoot.absolute.path); + final String relativePath = globals.fs.path.relative(srcFile.path, from: _flutterRoot.absolute.path); // Skip template files in both the ide_templates and templates // directories to avoid copying onto themselves. @@ -148,30 +148,30 @@ continue; } - final File finalDestinationFile = fs.file(fs.path.absolute( + final File finalDestinationFile = globals.fs.file(globals.fs.path.absolute( _templateDirectory.absolute.path, '$relativePath${Template.copyTemplateExtension}')); final String relativeDestination = - fs.path.relative(finalDestinationFile.path, from: _flutterRoot.absolute.path); + globals.fs.path.relative(finalDestinationFile.path, from: _flutterRoot.absolute.path); if (finalDestinationFile.existsSync()) { if (_fileIsIdentical(srcFile, finalDestinationFile)) { - printTrace(' $relativeDestination (identical)'); + globals.printTrace(' $relativeDestination (identical)'); manifest.add('$relativePath${Template.copyTemplateExtension}'); continue; } if (boolArg('overwrite')) { finalDestinationFile.deleteSync(); - printStatus(' $relativeDestination (overwritten)'); + globals.printStatus(' $relativeDestination (overwritten)'); } else { - printTrace(' $relativeDestination (existing - skipped)'); + globals.printTrace(' $relativeDestination (existing - skipped)'); manifest.add('$relativePath${Template.copyTemplateExtension}'); continue; } } else { - printStatus(' $relativeDestination (added)'); + globals.printStatus(' $relativeDestination (added)'); } - final Directory finalDestinationDir = fs.directory(finalDestinationFile.dirname); + final Directory finalDestinationDir = globals.fs.directory(finalDestinationFile.dirname); if (!finalDestinationDir.existsSync()) { - printTrace(" ${finalDestinationDir.path} doesn't exist, creating."); + globals.printTrace(" ${finalDestinationDir.path} doesn't exist, creating."); finalDestinationDir.createSync(recursive: true); } srcFile.copySync(finalDestinationFile.path); @@ -187,24 +187,24 @@ // them. final Iterable<File> templateFiles = _templateDirectory.listSync(recursive: true).whereType<File>(); for (File templateFile in templateFiles) { - final String relativePath = fs.path.relative( + final String relativePath = globals.fs.path.relative( templateFile.absolute.path, from: _templateDirectory.absolute.path, ); if (!manifest.contains(relativePath)) { templateFile.deleteSync(); final String relativeDestination = - fs.path.relative(templateFile.path, from: _flutterRoot.absolute.path); - printStatus(' $relativeDestination (removed)'); + globals.fs.path.relative(templateFile.path, from: _flutterRoot.absolute.path); + globals.printStatus(' $relativeDestination (removed)'); } // If the directory is now empty, then remove it, and do the same for its parent, // until we escape to the template directory. - Directory parentDir = fs.directory(templateFile.dirname); + Directory parentDir = globals.fs.directory(templateFile.dirname); while (parentDir.listSync().isEmpty) { parentDir.deleteSync(); - printTrace(' ${fs.path.relative(parentDir.absolute.path)} (empty directory - removed)'); - parentDir = fs.directory(parentDir.dirname); - if (fs.path.isWithin(_templateDirectory.absolute.path, parentDir.absolute.path)) { + globals.printTrace(' ${globals.fs.path.relative(parentDir.absolute.path)} (empty directory - removed)'); + parentDir = globals.fs.directory(parentDir.dirname); + if (globals.fs.path.isWithin(_templateDirectory.absolute.path, parentDir.absolute.path)) { break; } } @@ -222,9 +222,9 @@ return null; } - final String flutterRoot = fs.path.absolute(Cache.flutterRoot); - final String dirPath = fs.path.normalize( - fs.directory(fs.path.absolute(Cache.flutterRoot)).absolute.path, + final String flutterRoot = globals.fs.path.absolute(Cache.flutterRoot); + final String dirPath = globals.fs.path.normalize( + globals.fs.directory(globals.fs.path.absolute(Cache.flutterRoot)).absolute.path, ); final String error = _validateFlutterDir(dirPath, flutterRoot: flutterRoot); @@ -232,15 +232,15 @@ throwToolExit(error); } - printStatus('Updating IDE configuration for Flutter tree at $dirPath...'); + globals.printStatus('Updating IDE configuration for Flutter tree at $dirPath...'); int generatedCount = 0; generatedCount += _renderTemplate(_ideName, dirPath, <String, dynamic>{ 'withRootModule': boolArg('with-root-module'), }); - printStatus('Wrote $generatedCount files.'); - printStatus(''); - printStatus('Your IntelliJ configuration is now up to date. It is prudent to ' + globals.printStatus('Wrote $generatedCount files.'); + globals.printStatus(''); + globals.printStatus('Your IntelliJ configuration is now up to date. It is prudent to ' 'restart IntelliJ, if running.'); return null; @@ -249,7 +249,7 @@ int _renderTemplate(String templateName, String dirPath, Map<String, dynamic> context) { final Template template = Template(_templateDirectory, _templateDirectory); return template.render( - fs.directory(dirPath), + globals.fs.directory(dirPath), context, overwriteExisting: boolArg('overwrite'), ); @@ -259,7 +259,7 @@ /// Return null if the flutter root directory is a valid destination. Return a /// validation message if we should disallow the directory. String _validateFlutterDir(String dirPath, { String flutterRoot }) { - final FileSystemEntityType type = fs.typeSync(dirPath); + final FileSystemEntityType type = globals.fs.typeSync(dirPath); if (type != FileSystemEntityType.notFound) { switch (type) {
diff --git a/packages/flutter_tools/lib/src/commands/inject_plugins.dart b/packages/flutter_tools/lib/src/commands/inject_plugins.dart index 72aad34..285670d 100644 --- a/packages/flutter_tools/lib/src/commands/inject_plugins.dart +++ b/packages/flutter_tools/lib/src/commands/inject_plugins.dart
@@ -4,7 +4,7 @@ import 'dart:async'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../plugins.dart'; import '../project.dart'; import '../runner/flutter_command.dart'; @@ -33,9 +33,9 @@ await injectPlugins(project, checkProjects: true); final bool result = hasPlugins(project); if (result) { - printStatus('GeneratedPluginRegistrants successfully written.'); + globals.printStatus('GeneratedPluginRegistrants successfully written.'); } else { - printStatus('This project does not use plugins, no GeneratedPluginRegistrants have been created.'); + globals.printStatus('This project does not use plugins, no GeneratedPluginRegistrants have been created.'); } return null;
diff --git a/packages/flutter_tools/lib/src/commands/install.dart b/packages/flutter_tools/lib/src/commands/install.dart index 4ca851d..1a04de9 100644 --- a/packages/flutter_tools/lib/src/commands/install.dart +++ b/packages/flutter_tools/lib/src/commands/install.dart
@@ -8,7 +8,7 @@ import '../base/common.dart'; import '../cache.dart'; import '../device.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../runner/flutter_command.dart'; class InstallCommand extends FlutterCommand with DeviceBasedDevelopmentArtifacts { @@ -39,7 +39,7 @@ Cache.releaseLockEarly(); - printStatus('Installing $package to $device...'); + globals.printStatus('Installing $package to $device...'); if (!await installApp(device, package)) { throwToolExit('Install failed'); @@ -55,9 +55,9 @@ } if (uninstall && await device.isAppInstalled(package)) { - printStatus('Uninstalling old version...'); + globals.printStatus('Uninstalling old version...'); if (!await device.uninstallApp(package)) { - printError('Warning: uninstalling old version failed'); + globals.printError('Warning: uninstalling old version failed'); } }
diff --git a/packages/flutter_tools/lib/src/commands/logs.dart b/packages/flutter_tools/lib/src/commands/logs.dart index a38b614..8fefada 100644 --- a/packages/flutter_tools/lib/src/commands/logs.dart +++ b/packages/flutter_tools/lib/src/commands/logs.dart
@@ -8,7 +8,7 @@ import '../base/io.dart'; import '../cache.dart'; import '../device.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../runner/flutter_command.dart'; class LogsCommand extends FlutterCommand { @@ -50,13 +50,13 @@ Cache.releaseLockEarly(); - printStatus('Showing $logReader logs:'); + globals.printStatus('Showing $logReader logs:'); final Completer<int> exitCompleter = Completer<int>(); // Start reading. final StreamSubscription<String> subscription = logReader.logLines.listen( - (String message) => printStatus(message, wrap: false), + (String message) => globals.printStatus(message, wrap: false), onDone: () { exitCompleter.complete(0); }, @@ -68,7 +68,7 @@ // When terminating, close down the log reader. ProcessSignal.SIGINT.watch().listen((ProcessSignal signal) { subscription.cancel(); - printStatus(''); + globals.printStatus(''); exitCompleter.complete(0); }); ProcessSignal.SIGTERM.watch().listen((ProcessSignal signal) {
diff --git a/packages/flutter_tools/lib/src/commands/precache.dart b/packages/flutter_tools/lib/src/commands/precache.dart index dbcc92b..d9a6dd2 100644 --- a/packages/flutter_tools/lib/src/commands/precache.dart +++ b/packages/flutter_tools/lib/src/commands/precache.dart
@@ -6,7 +6,7 @@ import '../cache.dart'; import '../features.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../runner/flutter_command.dart'; import '../version.dart'; @@ -60,10 +60,10 @@ @override Future<FlutterCommandResult> runCommand() async { if (boolArg('all-platforms')) { - cache.includeAllPlatforms = true; + globals.cache.includeAllPlatforms = true; } if (boolArg('use-unsigned-mac-binaries')) { - cache.useUnsignedMacBinaries = true; + globals.cache.useUnsignedMacBinaries = true; } final Set<DevelopmentArtifact> requiredArtifacts = <DevelopmentArtifact>{}; for (DevelopmentArtifact artifact in DevelopmentArtifact.values) { @@ -83,10 +83,10 @@ } } final bool forceUpdate = boolArg('force'); - if (forceUpdate || !cache.isUpToDate()) { - await cache.updateAll(requiredArtifacts); + if (forceUpdate || !globals.cache.isUpToDate()) { + await globals.cache.updateAll(requiredArtifacts); } else { - printStatus('Already up-to-date.'); + globals.printStatus('Already up-to-date.'); } return null; }
diff --git a/packages/flutter_tools/lib/src/commands/run.dart b/packages/flutter_tools/lib/src/commands/run.dart index 811761e..0fe5581 100644 --- a/packages/flutter_tools/lib/src/commands/run.dart +++ b/packages/flutter_tools/lib/src/commands/run.dart
@@ -8,14 +8,13 @@ import '../base/common.dart'; import '../base/file_system.dart'; -import '../base/terminal.dart'; import '../base/time.dart'; import '../base/utils.dart'; import '../build_info.dart'; import '../cache.dart'; import '../device.dart'; import '../features.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../project.dart'; import '../reporting/reporting.dart'; import '../resident_runner.dart'; @@ -271,7 +270,7 @@ final Iterable<File> swiftFiles = iosProject.hostAppRoot .listSync(recursive: true, followLinks: false) .whereType<File>() - .where((File file) => fs.path.extension(file.path) == '.swift'); + .where((File file) => globals.fs.path.extension(file.path) == '.swift'); hostLanguage.add(swiftFiles.isNotEmpty ? 'swift' : 'objc'); } } @@ -395,11 +394,11 @@ try { final String applicationBinaryPath = stringArg('use-application-binary'); app = await daemon.appDomain.startApp( - devices.first, fs.currentDirectory.path, targetFile, route, + devices.first, globals.fs.currentDirectory.path, targetFile, route, _createDebuggingOptions(), hotMode, applicationBinary: applicationBinaryPath == null ? null - : fs.file(applicationBinaryPath), + : globals.fs.file(applicationBinaryPath), trackWidgetCreation: boolArg('track-widget-creation'), projectRootPath: stringArg('project-root'), packagesFilePath: globalResults['packages'] as String, @@ -420,7 +419,7 @@ endTimeOverride: appStartedTime, ); } - terminal.usesTerminalUi = true; + globals.terminal.usesTerminalUi = true; if (argResults['dart-flags'] != null && !FlutterVersion.instance.isMaster) { throw UsageException('--dart-flags is not available on the stable ' @@ -429,7 +428,7 @@ for (Device device in devices) { if (!device.supportsFastStart && boolArg('fast-start')) { - printStatus( + globals.printStatus( 'Using --fast-start option with device ${device.name}, but this device ' 'does not support it. Overriding the setting to false.' ); @@ -438,12 +437,12 @@ if (await device.supportsHardwareRendering) { final bool enableSoftwareRendering = boolArg('enable-software-rendering') == true; if (enableSoftwareRendering) { - printStatus( + globals.printStatus( 'Using software rendering with device ${device.name}. You may get better performance ' 'with hardware mode by configuring hardware rendering for your device.' ); } else { - printStatus( + globals.printStatus( 'Using hardware rendering with device ${device.name}. If you get graphics artifacts, ' 'consider enabling software rendering with "--enable-software-rendering".' ); @@ -501,7 +500,7 @@ benchmarkMode: boolArg('benchmark'), applicationBinary: applicationBinaryPath == null ? null - : fs.file(applicationBinaryPath), + : globals.fs.file(applicationBinaryPath), projectRootPath: stringArg('project-root'), packagesFilePath: globalResults['packages'] as String, dillOutputPath: stringArg('output-dill'), @@ -528,7 +527,7 @@ awaitFirstFrameWhenTracing: awaitFirstFrameWhenTracing, applicationBinary: applicationBinaryPath == null ? null - : fs.file(applicationBinaryPath), + : globals.fs.file(applicationBinaryPath), ipv6: ipv6, stayResident: stayResident, );
diff --git a/packages/flutter_tools/lib/src/commands/screenshot.dart b/packages/flutter_tools/lib/src/commands/screenshot.dart index 8f9b05b..47ec354 100644 --- a/packages/flutter_tools/lib/src/commands/screenshot.dart +++ b/packages/flutter_tools/lib/src/commands/screenshot.dart
@@ -9,7 +9,7 @@ import '../base/utils.dart'; import '../convert.dart'; import '../device.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../runner/flutter_command.dart'; import '../vmservice.dart'; @@ -91,7 +91,7 @@ Future<FlutterCommandResult> runCommand() async { File outputFile; if (argResults.wasParsed(_kOut)) { - outputFile = fs.file(stringArg(_kOut)); + outputFile = globals.fs.file(stringArg(_kOut)); } switch (stringArg(_kType)) { @@ -110,7 +110,7 @@ } Future<void> runScreenshot(File outputFile) async { - outputFile ??= getUniqueFile(fs.currentDirectory, 'flutter', 'png'); + outputFile ??= getUniqueFile(globals.fs.currentDirectory, 'flutter', 'png'); try { await device.takeScreenshot(outputFile); } catch (error) { @@ -121,7 +121,7 @@ Future<void> runSkia(File outputFile) async { final Map<String, dynamic> skp = await _invokeVmServiceRpc('_flutter.screenshotSkp'); - outputFile ??= getUniqueFile(fs.currentDirectory, 'flutter', 'skp'); + outputFile ??= getUniqueFile(globals.fs.currentDirectory, 'flutter', 'skp'); final IOSink sink = outputFile.openWrite(); sink.add(base64.decode(skp['skp'] as String)); await sink.close(); @@ -131,7 +131,7 @@ Future<void> runRasterizer(File outputFile) async { final Map<String, dynamic> response = await _invokeVmServiceRpc('_flutter.screenshot'); - outputFile ??= getUniqueFile(fs.currentDirectory, 'flutter', 'png'); + outputFile ??= getUniqueFile(globals.fs.currentDirectory, 'flutter', 'png'); final IOSink sink = outputFile.openWrite(); sink.add(base64.decode(response['screenshot'] as String)); await sink.close(); @@ -159,6 +159,6 @@ void _showOutputFileInfo(File outputFile) { final int sizeKB = (outputFile.lengthSync()) ~/ 1024; - printStatus('Screenshot written to ${fs.path.relative(outputFile.path)} (${sizeKB}kB).'); + globals.printStatus('Screenshot written to ${globals.fs.path.relative(outputFile.path)} (${sizeKB}kB).'); } }
diff --git a/packages/flutter_tools/lib/src/commands/shell_completion.dart b/packages/flutter_tools/lib/src/commands/shell_completion.dart index 27dfdc2..7cf89e5 100644 --- a/packages/flutter_tools/lib/src/commands/shell_completion.dart +++ b/packages/flutter_tools/lib/src/commands/shell_completion.dart
@@ -9,6 +9,7 @@ import '../base/common.dart'; import '../base/file_system.dart'; import '../base/io.dart'; +import '../globals.dart' as globals; import '../runner/flutter_command.dart'; class ShellCompletionCommand extends FlutterCommand { @@ -52,7 +53,7 @@ return null; } - final File outputFile = fs.file(argResults.rest.first); + final File outputFile = globals.fs.file(argResults.rest.first); if (outputFile.existsSync() && !boolArg('overwrite')) { throwToolExit( 'Output file ${outputFile.path} already exists, will not overwrite. '
diff --git a/packages/flutter_tools/lib/src/commands/test.dart b/packages/flutter_tools/lib/src/commands/test.dart index bedf99a..21e2e0f 100644 --- a/packages/flutter_tools/lib/src/commands/test.dart +++ b/packages/flutter_tools/lib/src/commands/test.dart
@@ -8,14 +8,13 @@ import '../asset.dart'; import '../base/common.dart'; import '../base/file_system.dart'; -import '../base/platform.dart'; import '../build_info.dart'; import '../bundle.dart'; import '../cache.dart'; import '../codegen.dart'; import '../dart/pub.dart'; import '../devfs.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../project.dart'; import '../runner/flutter_command.dart'; import '../test/coverage_collector.dart'; @@ -90,7 +89,7 @@ ) ..addOption('concurrency', abbr: 'j', - defaultsTo: math.max<int>(1, platform.numberOfProcessors - 2).toString(), + defaultsTo: math.max<int>(1, globals.platform.numberOfProcessors - 2).toString(), help: 'The number of concurrent test processes to run.', valueHelp: 'jobs', ) @@ -135,8 +134,8 @@ @override Future<FlutterCommandResult> runCommand() async { - await cache.updateAll(await requiredArtifacts); - if (!fs.isFileSync('pubspec.yaml')) { + await globals.cache.updateAll(await requiredArtifacts); + if (!globals.fs.isFileSync('pubspec.yaml')) { throwToolExit( 'Error: No pubspec.yaml file found in the current working directory.\n' 'Run this command from the root of your project. Test files must be ' @@ -155,7 +154,7 @@ await _buildTestAsset(); } - List<String> files = argResults.rest.map<String>((String testPath) => fs.path.absolute(testPath)).toList(); + List<String> files = argResults.rest.map<String>((String testPath) => globals.fs.path.absolute(testPath)).toList(); final bool startPaused = boolArg('start-paused'); if (startPaused && files.length != 1) { @@ -176,7 +175,7 @@ if (files.isEmpty) { // We don't scan the entire package, only the test/ subdirectory, so that // files with names like like "hit_test.dart" don't get run. - workDir = fs.directory('test'); + workDir = globals.fs.directory('test'); if (!workDir.existsSync()) { throwToolExit('Test directory "${workDir.path}" not found.'); } @@ -190,8 +189,8 @@ } else { files = <String>[ for (String path in files) - if (fs.isDirectorySync(path)) - ..._findTests(fs.directory(path)) + if (globals.fs.isDirectorySync(path)) + ..._findTests(globals.fs.directory(path)) else path, ]; @@ -281,18 +280,18 @@ throwToolExit('Error: Failed to build asset bundle'); } if (_needRebuild(assetBundle.entries)) { - await writeBundle(fs.directory(fs.path.join('build', 'unit_test_assets')), + await writeBundle(globals.fs.directory(globals.fs.path.join('build', 'unit_test_assets')), assetBundle.entries); } } bool _needRebuild(Map<String, DevFSContent> entries) { - final File manifest = fs.file(fs.path.join('build', 'unit_test_assets', 'AssetManifest.json')); + final File manifest = globals.fs.file(globals.fs.path.join('build', 'unit_test_assets', 'AssetManifest.json')); if (!manifest.existsSync()) { return true; } final DateTime lastModified = manifest.lastModifiedSync(); - final File pub = fs.file('pubspec.yaml'); + final File pub = globals.fs.file('pubspec.yaml'); if (pub.lastModifiedSync().isAfter(lastModified)) { return true; } @@ -311,6 +310,6 @@ Iterable<String> _findTests(Directory directory) { return directory.listSync(recursive: true, followLinks: false) .where((FileSystemEntity entity) => entity.path.endsWith('_test.dart') && - fs.isFileSync(entity.path)) - .map((FileSystemEntity entity) => fs.path.absolute(entity.path)); + globals.fs.isFileSync(entity.path)) + .map((FileSystemEntity entity) => globals.fs.path.absolute(entity.path)); }
diff --git a/packages/flutter_tools/lib/src/commands/unpack.dart b/packages/flutter_tools/lib/src/commands/unpack.dart index 5f2fec2..e2c228d 100644 --- a/packages/flutter_tools/lib/src/commands/unpack.dart +++ b/packages/flutter_tools/lib/src/commands/unpack.dart
@@ -7,7 +7,7 @@ import '../base/file_system.dart'; import '../build_info.dart'; import '../cache.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../runner/flutter_command.dart'; /// The directory in the Flutter cache for each platform's artifacts. @@ -73,14 +73,14 @@ Future<FlutterCommandResult> runCommand() async { final String targetName = stringArg('target-platform'); final String targetDirectory = stringArg('cache-dir'); - if (!fs.directory(targetDirectory).existsSync()) { - fs.directory(targetDirectory).createSync(recursive: true); + if (!globals.fs.directory(targetDirectory).existsSync()) { + globals.fs.directory(targetDirectory).createSync(recursive: true); } final TargetPlatform targetPlatform = getTargetPlatformForName(targetName); final ArtifactUnpacker flutterArtifactFetcher = ArtifactUnpacker(targetPlatform); bool success = true; - if (artifacts is LocalEngineArtifacts) { - final LocalEngineArtifacts localEngineArtifacts = artifacts as LocalEngineArtifacts; + if (globals.artifacts is LocalEngineArtifacts) { + final LocalEngineArtifacts localEngineArtifacts = globals.artifacts as LocalEngineArtifacts; success = flutterArtifactFetcher.copyLocalBuildArtifacts( localEngineArtifacts.engineOutPath, targetDirectory, @@ -124,9 +124,9 @@ throwToolExit('Unsupported target platform: $platform'); } final String targetHash = - readHashFileIfPossible(Cache.instance.getStampFileFor(cacheStamp)); + readHashFileIfPossible(globals.cache.getStampFileFor(cacheStamp)); if (targetHash == null) { - printError('Failed to find engine stamp file'); + globals.printError('Failed to find engine stamp file'); return false; } @@ -134,7 +134,7 @@ final String currentHash = _lastCopiedHash(targetDirectory); if (currentHash == null || targetHash != currentHash) { // Copy them to the target directory. - final String flutterCacheDirectory = fs.path.join( + final String flutterCacheDirectory = globals.fs.path.join( Cache.flutterRoot, 'bin', 'cache', @@ -146,13 +146,13 @@ return false; } _setLastCopiedHash(targetDirectory, targetHash); - printTrace('Copied artifacts for version $targetHash.'); + globals.printTrace('Copied artifacts for version $targetHash.'); } else { - printTrace('Artifacts for version $targetHash already present.'); + globals.printTrace('Artifacts for version $targetHash already present.'); } } catch (error, stackTrace) { - printError(stackTrace.toString()); - printError(error.toString()); + globals.printError(stackTrace.toString()); + globals.printError(error.toString()); return false; } return true; @@ -179,30 +179,30 @@ bool _copyArtifactFiles(String sourceDirectory, String targetDirectory) { final List<String> artifactFiles = artifactFilesByPlatform[platform]; if (artifactFiles == null) { - printError('Unsupported platform: $platform.'); + globals.printError('Unsupported platform: $platform.'); return false; } try { - fs.directory(targetDirectory).createSync(recursive: true); + globals.fs.directory(targetDirectory).createSync(recursive: true); for (final String entityName in artifactFiles) { - final String sourcePath = fs.path.join(sourceDirectory, entityName); - final String targetPath = fs.path.join(targetDirectory, entityName); + final String sourcePath = globals.fs.path.join(sourceDirectory, entityName); + final String targetPath = globals.fs.path.join(targetDirectory, entityName); if (entityName.endsWith('/')) { copyDirectorySync( - fs.directory(sourcePath), - fs.directory(targetPath), + globals.fs.directory(sourcePath), + globals.fs.directory(targetPath), ); } else { - fs.file(sourcePath) - .copySync(fs.path.join(targetDirectory, entityName)); + globals.fs.file(sourcePath) + .copySync(globals.fs.path.join(targetDirectory, entityName)); } } - printTrace('Copied artifacts from $sourceDirectory.'); + globals.printTrace('Copied artifacts from $sourceDirectory.'); } catch (e, stackTrace) { - printError(e.message as String); - printError(stackTrace.toString()); + globals.printError(e.message as String); + globals.printError(stackTrace.toString()); return false; } return true; @@ -211,7 +211,7 @@ /// Returns a File object for the file containing the last copied hash /// in [directory]. File _lastCopiedHashFile(String directory) { - return fs.file(fs.path.join(directory, '.last_artifact_version')); + return globals.fs.file(globals.fs.path.join(directory, '.last_artifact_version')); } /// Returns the hash of the artifacts last copied to [directory], or null if @@ -220,11 +220,11 @@ // Sanity check that at least one file is present; this won't catch every // case, but handles someone deleting all the non-hidden cached files to // force fresh copy. - final String artifactFilePath = fs.path.join( + final String artifactFilePath = globals.fs.path.join( directory, artifactFilesByPlatform[platform].first, ); - if (!fs.file(artifactFilePath).existsSync()) { + if (!globals.fs.file(artifactFilePath).existsSync()) { return null; } final File hashFile = _lastCopiedHashFile(directory);
diff --git a/packages/flutter_tools/lib/src/commands/update_packages.dart b/packages/flutter_tools/lib/src/commands/update_packages.dart index b7a3857..169e276 100644 --- a/packages/flutter_tools/lib/src/commands/update_packages.dart +++ b/packages/flutter_tools/lib/src/commands/update_packages.dart
@@ -11,10 +11,9 @@ import '../base/file_system.dart'; import '../base/logger.dart'; import '../base/net.dart'; -import '../base/platform.dart'; import '../cache.dart'; import '../dart/pub.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../runner/flutter_command.dart'; /// Map from package name to package version, used to artificially pin a pub @@ -89,17 +88,17 @@ final bool hidden; Future<void> _downloadCoverageData() async { - final Status status = logger.startProgress( + final Status status = globals.logger.startProgress( 'Downloading lcov data for package:flutter...', timeout: timeoutConfiguration.slowOperation, ); - final String urlBase = platform.environment['FLUTTER_STORAGE_BASE_URL'] ?? 'https://storage.googleapis.com'; + final String urlBase = globals.platform.environment['FLUTTER_STORAGE_BASE_URL'] ?? 'https://storage.googleapis.com'; final List<int> data = await fetchUrl(Uri.parse('$urlBase/flutter_infra/flutter/coverage/lcov.info')); - final String coverageDir = fs.path.join(Cache.flutterRoot, 'packages/flutter/coverage'); - fs.file(fs.path.join(coverageDir, 'lcov.base.info')) + final String coverageDir = globals.fs.path.join(Cache.flutterRoot, 'packages/flutter/coverage'); + globals.fs.file(globals.fs.path.join(coverageDir, 'lcov.base.info')) ..createSync(recursive: true) ..writeAsBytesSync(data, flush: true); - fs.file(fs.path.join(coverageDir, 'lcov.info')) + globals.fs.file(globals.fs.path.join(coverageDir, 'lcov.info')) ..createSync(recursive: true) ..writeAsBytesSync(data, flush: true); status.stop(); @@ -127,14 +126,14 @@ // ensure we only get flutter/packages packages.retainWhere((Directory directory) { return consumerPackages.any((String package) { - return directory.path.endsWith('packages${fs.path.separator}$package'); + return directory.path.endsWith('packages${globals.fs.path.separator}$package'); }); }); } if (isVerifyOnly) { bool needsUpdate = false; - printStatus('Verifying pubspecs...'); + globals.printStatus('Verifying pubspecs...'); for (Directory directory in packages) { PubspecYaml pubspec; try { @@ -142,11 +141,11 @@ } on String catch (message) { throwToolExit(message); } - printTrace('Reading pubspec.yaml from ${directory.path}'); + globals.printTrace('Reading pubspec.yaml from ${directory.path}'); if (pubspec.checksum.value == null) { // If the checksum is invalid or missing, we can just ask them run to run // upgrade again to compute it. - printError( + globals.printError( 'Warning: pubspec in ${directory.path} has out of date dependencies. ' 'Please run "flutter update-packages --force-upgrade" to update them correctly.' ); @@ -163,14 +162,14 @@ if (checksum != pubspec.checksum.value) { // If the checksum doesn't match, they may have added or removed some dependencies. // we need to run update-packages to recapture the transitive deps. - printError( + globals.printError( 'Warning: pubspec in ${directory.path} has invalid dependencies. ' 'Please run "flutter update-packages --force-upgrade" to update them correctly.' ); needsUpdate = true; } else { // everything is correct in the pubspec. - printTrace('pubspec in ${directory.path} is up to date!'); + globals.printTrace('pubspec in ${directory.path} is up to date!'); } } if (needsUpdate) { @@ -180,12 +179,12 @@ exitCode: 1, ); } - printStatus('All pubspecs were up to date.'); + globals.printStatus('All pubspecs were up to date.'); return null; } if (upgrade || isPrintPaths || isPrintTransitiveClosure) { - printStatus('Upgrading packages...'); + globals.printStatus('Upgrading packages...'); // This feature attempts to collect all the packages used across all the // pubspec.yamls in the repo (including via transitive dependencies), and // find the latest version of each that can be used while keeping each @@ -196,7 +195,7 @@ final Map<String, PubspecDependency> dependencies = <String, PubspecDependency>{}; final Set<String> specialDependencies = <String>{}; for (Directory directory in packages) { // these are all the directories with pubspec.yamls we care about - printTrace('Reading pubspec.yaml from: ${directory.path}'); + globals.printTrace('Reading pubspec.yaml from: ${directory.path}'); PubspecYaml pubspec; try { pubspec = PubspecYaml(directory); // this parses the pubspec.yaml @@ -242,7 +241,7 @@ // pub tool will attempt to bring these dependencies up to the most recent // possible versions while honoring all their constraints. final PubDependencyTree tree = PubDependencyTree(); // object to collect results - final Directory tempDir = fs.systemTempDirectory.createTempSync('flutter_update_packages.'); + final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_update_packages.'); try { final File fakePackage = _pubspecFor(tempDir); fakePackage.createSync(); @@ -288,7 +287,7 @@ if (isPrintTransitiveClosure) { tree._dependencyTree.forEach((String from, Set<String> to) { - printStatus('$from -> $to'); + globals.printStatus('$from -> $to'); }); return null; } @@ -327,7 +326,7 @@ await _downloadCoverageData(); final double seconds = timer.elapsedMilliseconds / 1000.0; - printStatus('\nRan \'pub\' $count time${count == 1 ? "" : "s"} and fetched coverage data in ${seconds.toStringAsFixed(1)}s.'); + globals.printStatus('\nRan \'pub\' $count time${count == 1 ? "" : "s"} and fetched coverage data in ${seconds.toStringAsFixed(1)}s.'); return null; } @@ -373,11 +372,11 @@ buf.write(' <- '); } } - printStatus(buf.toString(), wrap: false); + globals.printStatus(buf.toString(), wrap: false); } if (paths.isEmpty) { - printStatus('No paths found from $from to $to'); + globals.printStatus('No paths found from $from to $to'); } } } @@ -1048,8 +1047,8 @@ } if (_kind == DependencyKind.path && - !fs.path.isWithin(fs.path.join(Cache.flutterRoot, 'bin'), _lockTarget) && - fs.path.isWithin(Cache.flutterRoot, _lockTarget)) { + !globals.fs.path.isWithin(globals.fs.path.join(Cache.flutterRoot, 'bin'), _lockTarget) && + globals.fs.path.isWithin(Cache.flutterRoot, _lockTarget)) { return true; } @@ -1065,8 +1064,8 @@ assert(kind == DependencyKind.unknown); if (line.startsWith(_pathPrefix)) { // We're a path dependency; remember the (absolute) path. - _lockTarget = fs.path.canonicalize( - fs.path.absolute(fs.path.dirname(pubspecPath), line.substring(_pathPrefix.length, line.length)) + _lockTarget = globals.fs.path.canonicalize( + globals.fs.path.absolute(globals.fs.path.dirname(pubspecPath), line.substring(_pathPrefix.length, line.length)) ); _kind = DependencyKind.path; } else if (line.startsWith(_sdkPrefix)) { @@ -1135,7 +1134,7 @@ /// Generates the File object for the pubspec.yaml file of a given Directory. File _pubspecFor(Directory directory) { - return fs.file(fs.path.join(directory.path, 'pubspec.yaml')); + return globals.fs.file(globals.fs.path.join(directory.path, 'pubspec.yaml')); } /// Generates the source of a fake pubspec.yaml file given a list of @@ -1147,7 +1146,7 @@ result.writeln('dependencies:'); overrides.writeln('dependency_overrides:'); if (_kManuallyPinnedDependencies.isNotEmpty) { - printStatus('WARNING: the following packages use hard-coded version constraints:'); + globals.printStatus('WARNING: the following packages use hard-coded version constraints:'); final Set<String> allTransitive = <String>{ for (PubspecDependency dependency in dependencies) dependency.name, @@ -1155,12 +1154,12 @@ for (String package in _kManuallyPinnedDependencies.keys) { // Don't add pinned dependency if it is not in the set of all transitive dependencies. if (!allTransitive.contains(package)) { - printStatus('Skipping $package because it was not transitive'); + globals.printStatus('Skipping $package because it was not transitive'); continue; } final String version = _kManuallyPinnedDependencies[package]; result.writeln(' $package: $version'); - printStatus(' - $package: $version'); + globals.printStatus(' - $package: $version'); } } for (PubspecDependency dependency in dependencies) {
diff --git a/packages/flutter_tools/lib/src/commands/upgrade.dart b/packages/flutter_tools/lib/src/commands/upgrade.dart index 10f236e..03a2b36 100644 --- a/packages/flutter_tools/lib/src/commands/upgrade.dart +++ b/packages/flutter_tools/lib/src/commands/upgrade.dart
@@ -7,14 +7,12 @@ import 'package:meta/meta.dart'; import '../base/common.dart'; -import '../base/file_system.dart'; import '../base/io.dart'; import '../base/os.dart'; -import '../base/platform.dart'; import '../base/process.dart'; import '../cache.dart'; import '../dart/pub.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../persistent_tool_state.dart'; import '../runner/flutter_command.dart'; import '../version.dart'; @@ -119,8 +117,8 @@ final bool alreadyUpToDate = await attemptFastForward(flutterVersion); if (alreadyUpToDate) { // If the upgrade was a no op, then do not continue with the second half. - printStatus('Flutter is already up to date on channel ${flutterVersion.channel}'); - printStatus('$flutterVersion'); + globals.printStatus('Flutter is already up to date on channel ${flutterVersion.channel}'); + globals.printStatus('$flutterVersion'); } else { await flutterUpgradeContinue(); } @@ -129,14 +127,14 @@ Future<void> flutterUpgradeContinue() async { final int code = await processUtils.stream( <String>[ - fs.path.join('bin', 'flutter'), + globals.fs.path.join('bin', 'flutter'), 'upgrade', '--continue', '--no-version-check', ], workingDirectory: Cache.flutterRoot, allowReentrantFlutter: true, - environment: Map<String, String>.of(platform.environment), + environment: Map<String, String>.of(globals.platform.environment), ); if (code != 0) { throwToolExit(null, exitCode: code); @@ -227,7 +225,7 @@ /// If the user is on a deprecated channel, attempts to migrate them off of /// it. Future<void> upgradeChannel(FlutterVersion flutterVersion) async { - printStatus('Upgrading Flutter from ${Cache.flutterRoot}...'); + globals.printStatus('Upgrading Flutter from ${Cache.flutterRoot}...'); await ChannelCommand.upgradeChannel(); } @@ -255,7 +253,7 @@ alreadyUpToDate = newFlutterVersion.channel == oldFlutterVersion.channel && newFlutterVersion.frameworkRevision == oldFlutterVersion.frameworkRevision; } catch (e) { - printTrace('Failed to determine FlutterVersion after upgrade fast-forward: $e'); + globals.printTrace('Failed to determine FlutterVersion after upgrade fast-forward: $e'); } return alreadyUpToDate; } @@ -266,15 +264,15 @@ /// shell script re-entrantly here so that it will download the updated /// Dart and so forth if necessary. Future<void> precacheArtifacts() async { - printStatus(''); - printStatus('Upgrading engine...'); + globals.printStatus(''); + globals.printStatus('Upgrading engine...'); final int code = await processUtils.stream( <String>[ - fs.path.join('bin', 'flutter'), '--no-color', '--no-version-check', 'precache', + globals.fs.path.join('bin', 'flutter'), '--no-color', '--no-version-check', 'precache', ], workingDirectory: Cache.flutterRoot, allowReentrantFlutter: true, - environment: Map<String, String>.of(platform.environment), + environment: Map<String, String>.of(globals.platform.environment), ); if (code != 0) { throwToolExit(null, exitCode: code); @@ -283,22 +281,22 @@ /// Update the user's packages. Future<void> updatePackages(FlutterVersion flutterVersion) async { - printStatus(''); - printStatus(flutterVersion.toString()); + globals.printStatus(''); + globals.printStatus(flutterVersion.toString()); final String projectRoot = findProjectRoot(); if (projectRoot != null) { - printStatus(''); + globals.printStatus(''); await pub.get(context: PubContext.pubUpgrade, directory: projectRoot, upgrade: true, checkLastModified: false); } } /// Run flutter doctor in case requirements have changed. Future<void> runDoctor() async { - printStatus(''); - printStatus('Running flutter doctor...'); + globals.printStatus(''); + globals.printStatus('Running flutter doctor...'); await processUtils.stream( <String>[ - fs.path.join('bin', 'flutter'), '--no-version-check', 'doctor', + globals.fs.path.join('bin', 'flutter'), '--no-version-check', 'doctor', ], workingDirectory: Cache.flutterRoot, allowReentrantFlutter: true,
diff --git a/packages/flutter_tools/lib/src/commands/version.dart b/packages/flutter_tools/lib/src/commands/version.dart index e4f758d..dbba34a 100644 --- a/packages/flutter_tools/lib/src/commands/version.dart +++ b/packages/flutter_tools/lib/src/commands/version.dart
@@ -5,14 +5,13 @@ import 'dart:async'; import '../base/common.dart'; -import '../base/file_system.dart'; import '../base/io.dart'; import '../base/os.dart'; import '../base/process.dart'; import '../base/version.dart'; import '../cache.dart'; import '../dart/pub.dart'; -import '../globals.dart'; +import '../globals.dart' as globals; import '../runner/flutter_command.dart'; import '../version.dart'; @@ -57,12 +56,12 @@ Future<FlutterCommandResult> runCommand() async { final List<String> tags = await getTags(); if (argResults.rest.isEmpty) { - tags.forEach(printStatus); + tags.forEach(globals.printStatus); return const FlutterCommandResult(ExitStatus.success); } final String version = argResults.rest[0].replaceFirst('v', ''); if (!tags.contains('v$version')) { - printError('There is no version: $version'); + globals.printError('There is no version: $version'); } // check min supported version @@ -74,7 +73,7 @@ bool withForce = false; if (targetVersion < minSupportedVersion) { if (!boolArg('force')) { - printError( + globals.printError( 'Version command is not supported in $targetVersion and it is supported since version $minSupportedVersion' 'which means if you switch to version $minSupportedVersion then you can not use version command.' 'If you really want to switch to version $targetVersion, please use `--force` flag: `flutter version --force $targetVersion`.' @@ -96,16 +95,16 @@ final FlutterVersion flutterVersion = FlutterVersion(); - printStatus('Switching Flutter to version ${flutterVersion.frameworkVersion}${withForce ? ' with force' : ''}'); + globals.printStatus('Switching Flutter to version ${flutterVersion.frameworkVersion}${withForce ? ' with force' : ''}'); // Check for and download any engine and pkg/ updates. // We run the 'flutter' shell script re-entrantly here // so that it will download the updated Dart and so forth // if necessary. - printStatus(''); - printStatus('Downloading engine...'); + globals.printStatus(''); + globals.printStatus('Downloading engine...'); int code = await processUtils.stream(<String>[ - fs.path.join('bin', 'flutter'), + globals.fs.path.join('bin', 'flutter'), '--no-color', 'precache', ], workingDirectory: Cache.flutterRoot, allowReentrantFlutter: true); @@ -114,12 +113,12 @@ throwToolExit(null, exitCode: code); } - printStatus(''); - printStatus(flutterVersion.toString()); + globals.printStatus(''); + globals.printStatus(flutterVersion.toString()); final String projectRoot = findProjectRoot(); if (projectRoot != null && shouldRunPub) { - printStatus(''); + globals.printStatus(''); await pub.get( context: PubContext.pubUpgrade, directory: projectRoot, @@ -129,11 +128,11 @@ } // Run a doctor check in case system requirements have changed. - printStatus(''); - printStatus('Running flutter doctor...'); + globals.printStatus(''); + globals.printStatus('Running flutter doctor...'); code = await processUtils.stream( <String>[ - fs.path.join('bin', 'flutter'), + globals.fs.path.join('bin', 'flutter'), 'doctor', ], workingDirectory: Cache.flutterRoot,