Unverified Commit 0acd3e6b authored by Jonah Williams's avatar Jonah Williams Committed by GitHub

refactor context to be implicit-downcast safe (#31622)

parent 0e5d771a
...@@ -3,6 +3,12 @@ ...@@ -3,6 +3,12 @@
include: ../../analysis_options.yaml include: ../../analysis_options.yaml
analyzer:
strong-mode:
implicit-casts: true
implicit-dynamic: false
linter: linter:
rules: rules:
- unawaited_futures unawaited_futures: true
avoid_as: false # Disabled so we can gradually migrate to no implicit dynamic.
...@@ -17,7 +17,7 @@ import '../convert.dart'; ...@@ -17,7 +17,7 @@ import '../convert.dart';
import '../globals.dart'; import '../globals.dart';
import 'android_studio.dart' as android_studio; import 'android_studio.dart' as android_studio;
AndroidSdk get androidSdk => context[AndroidSdk]; AndroidSdk get androidSdk => context.get<AndroidSdk>();
const String kAndroidHome = 'ANDROID_HOME'; const String kAndroidHome = 'ANDROID_HOME';
const String kAndroidSdkRoot = 'ANDROID_SDK_ROOT'; const String kAndroidSdkRoot = 'ANDROID_SDK_ROOT';
......
...@@ -13,7 +13,7 @@ import '../globals.dart'; ...@@ -13,7 +13,7 @@ import '../globals.dart';
import '../ios/ios_workflow.dart'; import '../ios/ios_workflow.dart';
import '../ios/plist_utils.dart' as plist; import '../ios/plist_utils.dart' as plist;
AndroidStudio get androidStudio => context[AndroidStudio]; AndroidStudio get androidStudio => context.get<AndroidStudio>();
// Android Studio layout: // Android Studio layout:
......
...@@ -21,9 +21,9 @@ import 'android_sdk.dart'; ...@@ -21,9 +21,9 @@ import 'android_sdk.dart';
const int kAndroidSdkMinVersion = 28; const int kAndroidSdkMinVersion = 28;
final Version kAndroidSdkBuildToolsMinVersion = Version(28, 0, 3); final Version kAndroidSdkBuildToolsMinVersion = Version(28, 0, 3);
AndroidWorkflow get androidWorkflow => context[AndroidWorkflow]; AndroidWorkflow get androidWorkflow => context.get<AndroidWorkflow>();
AndroidValidator get androidValidator => context[AndroidValidator]; AndroidValidator get androidValidator => context.get<AndroidValidator>();
AndroidLicenseValidator get androidLicenseValidator => context[AndroidLicenseValidator]; AndroidLicenseValidator get androidLicenseValidator => context.get<AndroidLicenseValidator>();
enum LicensesAccepted { enum LicensesAccepted {
none, none,
......
...@@ -28,7 +28,7 @@ import 'web/web_device.dart'; ...@@ -28,7 +28,7 @@ import 'web/web_device.dart';
import 'windows/application_package.dart'; import 'windows/application_package.dart';
class ApplicationPackageFactory { class ApplicationPackageFactory {
static ApplicationPackageFactory get instance => context[ApplicationPackageFactory]; static ApplicationPackageFactory get instance => context.get<ApplicationPackageFactory>();
Future<ApplicationPackage> getPackageForPlatform( Future<ApplicationPackage> getPackageForPlatform(
TargetPlatform platform, { TargetPlatform platform, {
......
...@@ -100,7 +100,7 @@ class EngineBuildPaths { ...@@ -100,7 +100,7 @@ class EngineBuildPaths {
// Manages the engine artifacts of Flutter. // Manages the engine artifacts of Flutter.
abstract class Artifacts { abstract class Artifacts {
static Artifacts get instance => context[Artifacts]; static Artifacts get instance => context.get<Artifacts>();
static LocalEngineArtifacts getLocalEngine(String engineSrcPath, EngineBuildPaths engineBuildPaths) { static LocalEngineArtifacts getLocalEngine(String engineSrcPath, EngineBuildPaths engineBuildPaths) {
return LocalEngineArtifacts(engineSrcPath, engineBuildPaths.targetEngine, engineBuildPaths.hostEngine); return LocalEngineArtifacts(engineSrcPath, engineBuildPaths.targetEngine, engineBuildPaths.hostEngine);
......
...@@ -23,7 +23,7 @@ const AssetBundleFactory _kManifestFactory = _ManifestAssetBundleFactory(); ...@@ -23,7 +23,7 @@ const AssetBundleFactory _kManifestFactory = _ManifestAssetBundleFactory();
/// Injected factory class for spawning [AssetBundle] instances. /// Injected factory class for spawning [AssetBundle] instances.
abstract class AssetBundleFactory { abstract class AssetBundleFactory {
/// The singleton instance, pulled from the [AppContext]. /// The singleton instance, pulled from the [AppContext].
static AssetBundleFactory get instance => context[AssetBundleFactory]; static AssetBundleFactory get instance => context.get<AssetBundleFactory>();
static AssetBundleFactory get defaultInstance => _kManifestFactory; static AssetBundleFactory get defaultInstance => _kManifestFactory;
......
...@@ -21,7 +21,7 @@ import 'file_system.dart'; ...@@ -21,7 +21,7 @@ import 'file_system.dart';
import 'fingerprint.dart'; import 'fingerprint.dart';
import 'process.dart'; import 'process.dart';
GenSnapshot get genSnapshot => context[GenSnapshot]; GenSnapshot get genSnapshot => context.get<GenSnapshot>();
/// A snapshot build configuration. /// A snapshot build configuration.
class SnapshotType { class SnapshotType {
......
...@@ -14,7 +14,7 @@ class Config { ...@@ -14,7 +14,7 @@ class Config {
_values = json.decode(_configFile.readAsStringSync()); _values = json.decode(_configFile.readAsStringSync());
} }
static Config get instance => context[Config]; static Config get instance => context.get<Config>();
File _configFile; File _configFile;
String get configPath => _configFile.path; String get configPath => _configFile.path;
......
...@@ -33,7 +33,7 @@ class ContextDependencyCycleException implements Exception { ...@@ -33,7 +33,7 @@ class ContextDependencyCycleException implements Exception {
/// context will not have any values associated with it. /// context will not have any values associated with it.
/// ///
/// This is guaranteed to never return `null`. /// This is guaranteed to never return `null`.
AppContext get context => Zone.current[_Key.key] ?? AppContext._root; AppContext get context => Zone.current[_Key.key] as AppContext ?? AppContext._root;
/// A lookup table (mapping types to values) and an implied scope, in which /// A lookup table (mapping types to values) and an implied scope, in which
/// code is run. /// code is run.
...@@ -107,6 +107,17 @@ class AppContext { ...@@ -107,6 +107,17 @@ class AppContext {
/// Gets the value associated with the specified [type], or `null` if no /// Gets the value associated with the specified [type], or `null` if no
/// such value has been associated. /// such value has been associated.
T get<T>() {
dynamic value = _generateIfNecessary(T, _overrides);
if (value == null && _parent != null) {
value = _parent.get<T>();
}
return _unboxNull(value ?? _generateIfNecessary(T, _fallbacks)) as T;
}
/// Gets the value associated with the specified [type], or `null` if no
/// such value has been associated.
@Deprecated('use get<T> instead for type safety.')
Object operator [](Type type) { Object operator [](Type type) {
dynamic value = _generateIfNecessary(type, _overrides); dynamic value = _generateIfNecessary(type, _overrides);
if (value == null && _parent != null) if (value == null && _parent != null)
......
...@@ -23,7 +23,7 @@ const FileSystem _kLocalFs = LocalFileSystem(); ...@@ -23,7 +23,7 @@ const FileSystem _kLocalFs = LocalFileSystem();
/// ///
/// By default it uses local disk-based implementation. Override this in tests /// By default it uses local disk-based implementation. Override this in tests
/// with [MemoryFileSystem]. /// with [MemoryFileSystem].
FileSystem get fs => context[FileSystem] ?? _kLocalFs; FileSystem get fs => context.get<FileSystem>() ?? _kLocalFs;
/// Gets a [FileSystem] that will record file system activity to the specified /// Gets a [FileSystem] that will record file system activity to the specified
/// base recording [location]. /// base recording [location].
......
...@@ -8,7 +8,7 @@ import 'context.dart'; ...@@ -8,7 +8,7 @@ import 'context.dart';
/// command-line flags and options that were specified during the invocation of /// command-line flags and options that were specified during the invocation of
/// the Flutter tool. /// the Flutter tool.
Flags get flags => context[Flags]; Flags get flags => context.get<Flags>();
/// Encapsulation of the command-line flags and options that were specified /// Encapsulation of the command-line flags and options that were specified
/// during the invocation of the Flutter tool. /// during the invocation of the Flutter tool.
......
...@@ -163,7 +163,7 @@ class Stdio { ...@@ -163,7 +163,7 @@ class Stdio {
bool get supportsAnsiEscapes => hasTerminal ? io.stdout.supportsAnsiEscapes : false; bool get supportsAnsiEscapes => hasTerminal ? io.stdout.supportsAnsiEscapes : false;
} }
Stdio get stdio => context[Stdio]; Stdio get stdio => context.get<Stdio>();
io.IOSink get stdout => stdio.stdout; io.IOSink get stdout => stdio.stdout;
Stream<List<int>> get stdin => stdio.stdin; Stream<List<int>> get stdin => stdio.stdin;
io.IOSink get stderr => stdio.stderr; io.IOSink get stderr => stdio.stderr;
...@@ -19,7 +19,7 @@ const Duration _kSlowOperation = Duration(minutes: 2); ...@@ -19,7 +19,7 @@ const Duration _kSlowOperation = Duration(minutes: 2);
/// The [TimeoutConfiguration] instance. /// The [TimeoutConfiguration] instance.
/// ///
/// If not provided via injection, a default instance is provided. /// If not provided via injection, a default instance is provided.
TimeoutConfiguration get timeoutConfiguration => context[TimeoutConfiguration] ?? const TimeoutConfiguration(); TimeoutConfiguration get timeoutConfiguration => context.get<TimeoutConfiguration>() ?? const TimeoutConfiguration();
class TimeoutConfiguration { class TimeoutConfiguration {
const TimeoutConfiguration(); const TimeoutConfiguration();
...@@ -486,7 +486,7 @@ abstract class Status { ...@@ -486,7 +486,7 @@ abstract class Status {
final VoidCallback onFinish; final VoidCallback onFinish;
@protected @protected
final Stopwatch _stopwatch = context[Stopwatch] ?? Stopwatch(); final Stopwatch _stopwatch = context.get<Stopwatch>() ?? Stopwatch();
@protected @protected
@visibleForTesting @visibleForTesting
......
...@@ -36,8 +36,8 @@ Future<bool> doesRemoteFileExist(Uri url) async => ...@@ -36,8 +36,8 @@ Future<bool> doesRemoteFileExist(Uri url) async =>
Future<List<int>> _attempt(Uri url, { bool onlyHeaders = false }) async { Future<List<int>> _attempt(Uri url, { bool onlyHeaders = false }) async {
printTrace('Downloading: $url'); printTrace('Downloading: $url');
HttpClient httpClient; HttpClient httpClient;
if (context[HttpClientFactory] != null) { if (context.get<HttpClientFactory>() != null) {
httpClient = (context[HttpClientFactory] as HttpClientFactory)(); // ignore: avoid_as httpClient = context.get<HttpClientFactory>()();
} else { } else {
httpClient = HttpClient(); httpClient = HttpClient();
} }
......
...@@ -11,7 +11,7 @@ import 'process.dart'; ...@@ -11,7 +11,7 @@ import 'process.dart';
import 'process_manager.dart'; import 'process_manager.dart';
/// Returns [OperatingSystemUtils] active in the current app context (i.e. zone). /// Returns [OperatingSystemUtils] active in the current app context (i.e. zone).
OperatingSystemUtils get os => context[OperatingSystemUtils]; OperatingSystemUtils get os => context.get<OperatingSystemUtils>();
abstract class OperatingSystemUtils { abstract class OperatingSystemUtils {
factory OperatingSystemUtils() { factory OperatingSystemUtils() {
......
...@@ -14,7 +14,7 @@ export 'package:platform/platform.dart'; ...@@ -14,7 +14,7 @@ export 'package:platform/platform.dart';
const Platform _kLocalPlatform = LocalPlatform(); const Platform _kLocalPlatform = LocalPlatform();
const String _kRecordingType = 'platform'; const String _kRecordingType = 'platform';
Platform get platform => context[Platform] ?? _kLocalPlatform; Platform get platform => context.get<Platform>() ?? _kLocalPlatform;
/// Serializes the current [platform] to the specified base recording /// Serializes the current [platform] to the specified base recording
/// [location]. /// [location].
......
...@@ -16,7 +16,7 @@ const String _kRecordingType = 'process'; ...@@ -16,7 +16,7 @@ const String _kRecordingType = 'process';
const ProcessManager _kLocalProcessManager = LocalProcessManager(); const ProcessManager _kLocalProcessManager = LocalProcessManager();
/// The active process manager. /// The active process manager.
ProcessManager get processManager => context[ProcessManager] ?? _kLocalProcessManager; ProcessManager get processManager => context.get<ProcessManager>() ?? _kLocalProcessManager;
/// Gets a [ProcessManager] that will record process invocation activity to the /// Gets a [ProcessManager] that will record process invocation activity to the
/// specified base recording [location]. /// specified base recording [location].
......
...@@ -14,9 +14,9 @@ import 'utils.dart'; ...@@ -14,9 +14,9 @@ import 'utils.dart';
final AnsiTerminal _kAnsiTerminal = AnsiTerminal(); final AnsiTerminal _kAnsiTerminal = AnsiTerminal();
AnsiTerminal get terminal { AnsiTerminal get terminal {
return (context == null || context[AnsiTerminal] == null) return (context == null || context.get<AnsiTerminal>() == null)
? _kAnsiTerminal ? _kAnsiTerminal
: context[AnsiTerminal]; : context.get<AnsiTerminal>();
} }
enum TerminalColor { enum TerminalColor {
...@@ -31,9 +31,9 @@ enum TerminalColor { ...@@ -31,9 +31,9 @@ enum TerminalColor {
final OutputPreferences _kOutputPreferences = OutputPreferences(); final OutputPreferences _kOutputPreferences = OutputPreferences();
OutputPreferences get outputPreferences => (context == null || context[OutputPreferences] == null) OutputPreferences get outputPreferences => (context == null || context.get<OutputPreferences>() == null)
? _kOutputPreferences ? _kOutputPreferences
: context[OutputPreferences]; : context.get<OutputPreferences>();
/// A class that contains the context settings for command text output to the /// A class that contains the context settings for command text output to the
/// console. /// console.
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
import 'context.dart'; import 'context.dart';
/// The current system clock instance. /// The current system clock instance.
SystemClock get systemClock => context[SystemClock]; SystemClock get systemClock => context.get<SystemClock>();
/// A class for making time based operations testable. /// A class for making time based operations testable.
class SystemClock { class SystemClock {
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
import 'context.dart'; import 'context.dart';
UserMessages get userMessages => context[UserMessages]; UserMessages get userMessages => context.get<UserMessages>();
/// Class containing message strings that can be produced by Flutter tools. /// Class containing message strings that can be produced by Flutter tools.
class UserMessages { class UserMessages {
......
...@@ -49,7 +49,7 @@ class BotDetector { ...@@ -49,7 +49,7 @@ class BotDetector {
} }
bool get isRunningOnBot { bool get isRunningOnBot {
final BotDetector botDetector = context[BotDetector] ?? _kBotDetector; final BotDetector botDetector = context.get<BotDetector>() ?? _kBotDetector;
return botDetector.isRunningOnBot; return botDetector.isRunningOnBot;
} }
......
...@@ -197,7 +197,7 @@ class Cache { ...@@ -197,7 +197,7 @@ class Cache {
} }
String _fuchsiaRevision; String _fuchsiaRevision;
static Cache get instance => context[Cache]; static Cache get instance => context.get<Cache>();
/// Return the top-level directory in the cache; this is `bin/cache`. /// Return the top-level directory in the cache; this is `bin/cache`.
Directory getRoot() { Directory getRoot() {
......
...@@ -22,7 +22,7 @@ const String kMultiRootScheme = 'org-dartlang-app'; ...@@ -22,7 +22,7 @@ const String kMultiRootScheme = 'org-dartlang-app';
/// ///
/// If [experimentalBuildEnabled] is false, this will contain an unsupported /// If [experimentalBuildEnabled] is false, this will contain an unsupported
/// implementation. /// implementation.
CodeGenerator get codeGenerator => context[CodeGenerator]; CodeGenerator get codeGenerator => context.get<CodeGenerator>();
/// A wrapper for a build_runner process which delegates to a generated /// A wrapper for a build_runner process which delegates to a generated
/// build script. /// build script.
......
...@@ -23,7 +23,7 @@ import 'dart/package_map.dart'; ...@@ -23,7 +23,7 @@ import 'dart/package_map.dart';
import 'globals.dart'; import 'globals.dart';
import 'project.dart'; import 'project.dart';
KernelCompilerFactory get kernelCompilerFactory => context[KernelCompilerFactory]; KernelCompilerFactory get kernelCompilerFactory => context.get<KernelCompilerFactory>();
class KernelCompilerFactory { class KernelCompilerFactory {
const KernelCompilerFactory(); const KernelCompilerFactory();
......
...@@ -26,7 +26,7 @@ class DevFSConfig { ...@@ -26,7 +26,7 @@ class DevFSConfig {
bool noDirectorySymlinks = false; bool noDirectorySymlinks = false;
} }
DevFSConfig get devFSConfig => context[DevFSConfig]; DevFSConfig get devFSConfig => context.get<DevFSConfig>();
/// Common superclass for content copied to the device. /// Common superclass for content copied to the device.
abstract class DevFSContent { abstract class DevFSContent {
......
...@@ -24,7 +24,7 @@ import 'tester/flutter_tester.dart'; ...@@ -24,7 +24,7 @@ import 'tester/flutter_tester.dart';
import 'web/web_device.dart'; import 'web/web_device.dart';
import 'windows/windows_device.dart'; import 'windows/windows_device.dart';
DeviceManager get deviceManager => context[DeviceManager]; DeviceManager get deviceManager => context.get<DeviceManager>();
/// A class to get all available devices. /// A class to get all available devices.
class DeviceManager { class DeviceManager {
......
...@@ -33,11 +33,11 @@ import 'version.dart'; ...@@ -33,11 +33,11 @@ import 'version.dart';
import 'vscode/vscode_validator.dart'; import 'vscode/vscode_validator.dart';
import 'windows/windows_workflow.dart'; import 'windows/windows_workflow.dart';
Doctor get doctor => context[Doctor]; Doctor get doctor => context.get<Doctor>();
abstract class DoctorValidatorsProvider { abstract class DoctorValidatorsProvider {
/// The singleton instance, pulled from the [AppContext]. /// The singleton instance, pulled from the [AppContext].
static DoctorValidatorsProvider get instance => context[DoctorValidatorsProvider]; static DoctorValidatorsProvider get instance => context.get<DoctorValidatorsProvider>();
static final DoctorValidatorsProvider defaultInstance = _DefaultDoctorValidatorsProvider(); static final DoctorValidatorsProvider defaultInstance = _DefaultDoctorValidatorsProvider();
......
...@@ -13,7 +13,7 @@ import 'base/process_manager.dart'; ...@@ -13,7 +13,7 @@ import 'base/process_manager.dart';
import 'globals.dart'; import 'globals.dart';
import 'ios/ios_emulators.dart'; import 'ios/ios_emulators.dart';
EmulatorManager get emulatorManager => context[EmulatorManager]; EmulatorManager get emulatorManager => context.get<EmulatorManager>();
/// A class to get all available emulators. /// A class to get all available emulators.
class EmulatorManager { class EmulatorManager {
......
...@@ -13,10 +13,10 @@ import '../convert.dart'; ...@@ -13,10 +13,10 @@ import '../convert.dart';
import '../globals.dart'; import '../globals.dart';
/// The [FuchsiaSdk] instance. /// The [FuchsiaSdk] instance.
FuchsiaSdk get fuchsiaSdk => context[FuchsiaSdk]; FuchsiaSdk get fuchsiaSdk => context.get<FuchsiaSdk>();
/// The [FuchsiaArtifacts] instance. /// The [FuchsiaArtifacts] instance.
FuchsiaArtifacts get fuchsiaArtifacts => context[FuchsiaArtifacts]; FuchsiaArtifacts get fuchsiaArtifacts => context.get<FuchsiaArtifacts>();
/// The Fuchsia SDK shell commands. /// The Fuchsia SDK shell commands.
/// ///
......
...@@ -8,7 +8,7 @@ import '../doctor.dart'; ...@@ -8,7 +8,7 @@ import '../doctor.dart';
import 'fuchsia_sdk.dart'; import 'fuchsia_sdk.dart';
/// The [FuchsiaWorkflow] instance. /// The [FuchsiaWorkflow] instance.
FuchsiaWorkflow get fuchsiaWorkflow => context[FuchsiaWorkflow]; FuchsiaWorkflow get fuchsiaWorkflow => context.get<FuchsiaWorkflow>();
/// The Fuchsia-specific implementation of a [Workflow]. /// The Fuchsia-specific implementation of a [Workflow].
/// ///
......
...@@ -9,7 +9,7 @@ import 'base/logger.dart'; ...@@ -9,7 +9,7 @@ import 'base/logger.dart';
import 'base/terminal.dart'; import 'base/terminal.dart';
import 'cache.dart'; import 'cache.dart';
Logger get logger => context[Logger]; Logger get logger => context.get<Logger>();
Cache get cache => Cache.instance; Cache get cache => Cache.instance;
Config get config => Config.instance; Config get config => Config.instance;
Artifacts get artifacts => Artifacts.instance; Artifacts get artifacts => Artifacts.instance;
......
...@@ -37,7 +37,7 @@ const String cocoaPodsUpgradeInstructions = ''' ...@@ -37,7 +37,7 @@ const String cocoaPodsUpgradeInstructions = '''
brew upgrade cocoapods brew upgrade cocoapods
pod setup'''; pod setup''';
CocoaPods get cocoaPods => context[CocoaPods]; CocoaPods get cocoaPods => context.get<CocoaPods>();
/// Result of evaluating the CocoaPods installation. /// Result of evaluating the CocoaPods installation.
enum CocoaPodsStatus { enum CocoaPodsStatus {
......
...@@ -15,9 +15,9 @@ import 'cocoapods.dart'; ...@@ -15,9 +15,9 @@ import 'cocoapods.dart';
import 'mac.dart'; import 'mac.dart';
import 'plist_utils.dart' as plist; import 'plist_utils.dart' as plist;
IOSWorkflow get iosWorkflow => context[IOSWorkflow]; IOSWorkflow get iosWorkflow => context.get<IOSWorkflow>();
IOSValidator get iosValidator => context[IOSValidator]; IOSValidator get iosValidator => context.get<IOSValidator>();
CocoaPodsValidator get cocoapodsValidator => context[CocoaPodsValidator]; CocoaPodsValidator get cocoapodsValidator => context.get<CocoaPodsValidator>();
class IOSWorkflow implements Workflow { class IOSWorkflow implements Workflow {
const IOSWorkflow(); const IOSWorkflow();
......
...@@ -31,9 +31,9 @@ import 'xcodeproj.dart'; ...@@ -31,9 +31,9 @@ import 'xcodeproj.dart';
const int kXcodeRequiredVersionMajor = 9; const int kXcodeRequiredVersionMajor = 9;
const int kXcodeRequiredVersionMinor = 0; const int kXcodeRequiredVersionMinor = 0;
IMobileDevice get iMobileDevice => context[IMobileDevice]; IMobileDevice get iMobileDevice => context.get<IMobileDevice>();
PlistBuddy get plistBuddy => context[PlistBuddy]; PlistBuddy get plistBuddy => context.get<PlistBuddy>();
Xcode get xcode => context[Xcode]; Xcode get xcode => context.get<Xcode>();
class PlistBuddy { class PlistBuddy {
const PlistBuddy(); const PlistBuddy();
......
...@@ -41,7 +41,7 @@ class IOSSimulators extends PollingDeviceDiscovery { ...@@ -41,7 +41,7 @@ class IOSSimulators extends PollingDeviceDiscovery {
class IOSSimulatorUtils { class IOSSimulatorUtils {
/// Returns [IOSSimulatorUtils] active in the current app context (i.e. zone). /// Returns [IOSSimulatorUtils] active in the current app context (i.e. zone).
static IOSSimulatorUtils get instance => context[IOSSimulatorUtils]; static IOSSimulatorUtils get instance => context.get<IOSSimulatorUtils>();
List<IOSSimulator> getAttachedDevices() { List<IOSSimulator> getAttachedDevices() {
if (!xcode.isInstalledAndMeetsVersionCheck) if (!xcode.isInstalledAndMeetsVersionCheck)
...@@ -56,7 +56,7 @@ class IOSSimulatorUtils { ...@@ -56,7 +56,7 @@ class IOSSimulatorUtils {
/// A wrapper around the `simctl` command line tool. /// A wrapper around the `simctl` command line tool.
class SimControl { class SimControl {
/// Returns [SimControl] active in the current app context (i.e. zone). /// Returns [SimControl] active in the current app context (i.e. zone).
static SimControl get instance => context[SimControl]; static SimControl get instance => context.get<SimControl>();
/// Runs `simctl list --json` and returns the JSON of the corresponding /// Runs `simctl list --json` and returns the JSON of the corresponding
/// [section]. /// [section].
......
...@@ -127,7 +127,7 @@ Future<void> updateGeneratedXcodeProperties({ ...@@ -127,7 +127,7 @@ Future<void> updateGeneratedXcodeProperties({
generatedXcodePropertiesFile.writeAsStringSync(localsBuffer.toString()); generatedXcodePropertiesFile.writeAsStringSync(localsBuffer.toString());
} }
XcodeProjectInterpreter get xcodeProjectInterpreter => context[XcodeProjectInterpreter]; XcodeProjectInterpreter get xcodeProjectInterpreter => context.get<XcodeProjectInterpreter>();
/// Interpreter of Xcode projects. /// Interpreter of Xcode projects.
class XcodeProjectInterpreter { class XcodeProjectInterpreter {
......
...@@ -8,7 +8,7 @@ import '../desktop.dart'; ...@@ -8,7 +8,7 @@ import '../desktop.dart';
import '../doctor.dart'; import '../doctor.dart';
/// The [WindowsWorkflow] instance. /// The [WindowsWorkflow] instance.
LinuxWorkflow get linuxWorkflow => context[LinuxWorkflow]; LinuxWorkflow get linuxWorkflow => context.get<LinuxWorkflow>();
/// The windows-specific implementation of a [Workflow]. /// The windows-specific implementation of a [Workflow].
/// ///
......
...@@ -8,7 +8,7 @@ import '../desktop.dart'; ...@@ -8,7 +8,7 @@ import '../desktop.dart';
import '../doctor.dart'; import '../doctor.dart';
/// The [MacOSWorkflow] instance. /// The [MacOSWorkflow] instance.
MacOSWorkflow get macOSWorkflow => context[MacOSWorkflow]; MacOSWorkflow get macOSWorkflow => context.get<MacOSWorkflow>();
/// The macOS-specific implementation of a [Workflow]. /// The macOS-specific implementation of a [Workflow].
/// ///
......
...@@ -40,7 +40,7 @@ class HotRunnerConfig { ...@@ -40,7 +40,7 @@ class HotRunnerConfig {
} }
} }
HotRunnerConfig get hotRunnerConfig => context[HotRunnerConfig]; HotRunnerConfig get hotRunnerConfig => context.get<HotRunnerConfig>();
const bool kHotReloadDefault = true; const bool kHotReloadDefault = true;
......
...@@ -77,7 +77,7 @@ abstract class FlutterCommand extends Command<void> { ...@@ -77,7 +77,7 @@ abstract class FlutterCommand extends Command<void> {
/// The currently executing command (or sub-command). /// The currently executing command (or sub-command).
/// ///
/// Will be `null` until the top-most command has begun execution. /// Will be `null` until the top-most command has begun execution.
static FlutterCommand get current => context[FlutterCommand]; static FlutterCommand get current => context.get<FlutterCommand>();
/// The option name for a custom observatory port. /// The option name for a custom observatory port.
static const String observatoryPortOption = 'observatory-port'; static const String observatoryPortOption = 'observatory-port';
......
...@@ -55,7 +55,7 @@ class Usage { ...@@ -55,7 +55,7 @@ class Usage {
} }
/// Returns [Usage] active in the current app context. /// Returns [Usage] active in the current app context.
static Usage get instance => context[Usage]; static Usage get instance => context.get<Usage>();
Analytics _analytics; Analytics _analytics;
......
...@@ -179,7 +179,7 @@ class FlutterVersion { ...@@ -179,7 +179,7 @@ class FlutterVersion {
await _run(<String>['git', 'remote', 'remove', _versionCheckRemote]); await _run(<String>['git', 'remote', 'remove', _versionCheckRemote]);
} }
static FlutterVersion get instance => context[FlutterVersion]; static FlutterVersion get instance => context.get<FlutterVersion>();
/// Return a short string for the version (e.g. `master/0.0.59-pre.92`, `scroll_refactor/a76bc8e22b`). /// Return a short string for the version (e.g. `master/0.0.59-pre.92`, `scroll_refactor/a76bc8e22b`).
String getVersionString({ bool redactUnknownBranches = false }) { String getVersionString({ bool redactUnknownBranches = false }) {
......
...@@ -82,7 +82,7 @@ Future<StreamChannel<String>> _defaultOpenChannel(Uri uri, {io.CompressionOption ...@@ -82,7 +82,7 @@ Future<StreamChannel<String>> _defaultOpenChannel(Uri uri, {io.CompressionOption
delay *= 2; delay *= 2;
} }
final WebSocketConnector constructor = context[WebSocketConnector] ?? io.WebSocket.connect; final WebSocketConnector constructor = context.get<WebSocketConnector>() ?? io.WebSocket.connect;
while (socket == null) { while (socket == null) {
attempts += 1; attempts += 1;
try { try {
......
...@@ -15,7 +15,7 @@ import '../convert.dart'; ...@@ -15,7 +15,7 @@ import '../convert.dart';
import '../globals.dart'; import '../globals.dart';
/// The [WebCompiler] instance. /// The [WebCompiler] instance.
WebCompiler get webCompiler => context[WebCompiler]; WebCompiler get webCompiler => context.get<WebCompiler>();
/// A wrapper around dart2js for web compilation. /// A wrapper around dart2js for web compilation.
class WebCompiler { class WebCompiler {
......
...@@ -16,7 +16,7 @@ import '../project.dart'; ...@@ -16,7 +16,7 @@ import '../project.dart';
import '../version.dart'; import '../version.dart';
import '../web/compile.dart'; import '../web/compile.dart';
ChromeLauncher get chromeLauncher => context[ChromeLauncher]; ChromeLauncher get chromeLauncher => context.get<ChromeLauncher>();
/// Only launch or display web devices if `FLUTTER_WEB` /// Only launch or display web devices if `FLUTTER_WEB`
/// environment variable is set to true. /// environment variable is set to true.
......
...@@ -8,7 +8,7 @@ import '../desktop.dart'; ...@@ -8,7 +8,7 @@ import '../desktop.dart';
import '../doctor.dart'; import '../doctor.dart';
/// The [WindowsWorkflow] instance. /// The [WindowsWorkflow] instance.
WindowsWorkflow get windowsWorkflow => context[WindowsWorkflow]; WindowsWorkflow get windowsWorkflow => context.get<WindowsWorkflow>();
/// The windows-specific implementation of a [Workflow]. /// The windows-specific implementation of a [Workflow].
/// ///
......
...@@ -146,21 +146,21 @@ void main() { ...@@ -146,21 +146,21 @@ void main() {
testUsingContext('Error when parsing manifest with no Activity that has enabled set to true nor has no value for its enabled field', () { testUsingContext('Error when parsing manifest with no Activity that has enabled set to true nor has no value for its enabled field', () {
final ApkManifestData data = ApkManifestData.parseFromXmlDump(_aaptDataWithNoEnabledActivity); final ApkManifestData data = ApkManifestData.parseFromXmlDump(_aaptDataWithNoEnabledActivity);
expect(data, isNull); expect(data, isNull);
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
expect( expect(
logger.errorText, 'Error running io.flutter.examples.hello_world. Default activity not found\n'); logger.errorText, 'Error running io.flutter.examples.hello_world. Default activity not found\n');
}, overrides: noColorTerminalOverride); }, overrides: noColorTerminalOverride);
testUsingContext('Error when parsing manifest with no Activity that has action set to android.intent.action.MAIN', () { testUsingContext('Error when parsing manifest with no Activity that has action set to android.intent.action.MAIN', () {
final ApkManifestData data = ApkManifestData.parseFromXmlDump(_aaptDataWithNoMainActivity); final ApkManifestData data = ApkManifestData.parseFromXmlDump(_aaptDataWithNoMainActivity);
expect(data, isNull); expect(data, isNull);
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
expect( expect(
logger.errorText, 'Error running io.flutter.examples.hello_world. Default activity not found\n'); logger.errorText, 'Error running io.flutter.examples.hello_world. Default activity not found\n');
}, overrides: noColorTerminalOverride); }, overrides: noColorTerminalOverride);
testUsingContext('Error when parsing manifest with no Activity that has category set to android.intent.category.LAUNCHER', () { testUsingContext('Error when parsing manifest with no Activity that has category set to android.intent.category.LAUNCHER', () {
final ApkManifestData data = ApkManifestData.parseFromXmlDump(_aaptDataWithNoLauncherActivity); final ApkManifestData data = ApkManifestData.parseFromXmlDump(_aaptDataWithNoLauncherActivity);
expect(data, isNull); expect(data, isNull);
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
expect( expect(
logger.errorText, 'Error running io.flutter.examples.hello_world. Default activity not found\n'); logger.errorText, 'Error running io.flutter.examples.hello_world. Default activity not found\n');
}, overrides: noColorTerminalOverride); }, overrides: noColorTerminalOverride);
...@@ -176,7 +176,7 @@ void main() { ...@@ -176,7 +176,7 @@ void main() {
final PrebuiltIOSApp iosApp = final PrebuiltIOSApp iosApp =
IOSApp.fromPrebuiltApp(fs.file('not_existing.ipa')); IOSApp.fromPrebuiltApp(fs.file('not_existing.ipa'));
expect(iosApp, isNull); expect(iosApp, isNull);
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
expect( expect(
logger.errorText, logger.errorText,
'File "not_existing.ipa" does not exist. Use an app bundle or an ipa.\n', 'File "not_existing.ipa" does not exist. Use an app bundle or an ipa.\n',
...@@ -187,7 +187,7 @@ void main() { ...@@ -187,7 +187,7 @@ void main() {
final PrebuiltIOSApp iosApp = final PrebuiltIOSApp iosApp =
IOSApp.fromPrebuiltApp(fs.file('regular_folder')); IOSApp.fromPrebuiltApp(fs.file('regular_folder'));
expect(iosApp, isNull); expect(iosApp, isNull);
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
expect( expect(
logger.errorText, 'Folder "regular_folder" is not an app bundle.\n'); logger.errorText, 'Folder "regular_folder" is not an app bundle.\n');
}, overrides: overrides); }, overrides: overrides);
...@@ -195,7 +195,7 @@ void main() { ...@@ -195,7 +195,7 @@ void main() {
fs.directory('bundle.app').createSync(); fs.directory('bundle.app').createSync();
final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('bundle.app')); final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('bundle.app'));
expect(iosApp, isNull); expect(iosApp, isNull);
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
expect( expect(
logger.errorText, logger.errorText,
'Invalid prebuilt iOS app. Does not contain Info.plist.\n', 'Invalid prebuilt iOS app. Does not contain Info.plist.\n',
...@@ -206,7 +206,7 @@ void main() { ...@@ -206,7 +206,7 @@ void main() {
fs.file('bundle.app/Info.plist').writeAsStringSync(badPlistData); fs.file('bundle.app/Info.plist').writeAsStringSync(badPlistData);
final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('bundle.app')); final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('bundle.app'));
expect(iosApp, isNull); expect(iosApp, isNull);
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
expect( expect(
logger.errorText, logger.errorText,
contains( contains(
...@@ -217,7 +217,7 @@ void main() { ...@@ -217,7 +217,7 @@ void main() {
fs.directory('bundle.app').createSync(); fs.directory('bundle.app').createSync();
fs.file('bundle.app/Info.plist').writeAsStringSync(plistData); fs.file('bundle.app/Info.plist').writeAsStringSync(plistData);
final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('bundle.app')); final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('bundle.app'));
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
expect(logger.errorText, isEmpty); expect(logger.errorText, isEmpty);
expect(iosApp.bundleDir.path, 'bundle.app'); expect(iosApp.bundleDir.path, 'bundle.app');
expect(iosApp.id, 'fooBundleId'); expect(iosApp.id, 'fooBundleId');
...@@ -228,7 +228,7 @@ void main() { ...@@ -228,7 +228,7 @@ void main() {
when(os.unzip(fs.file('app.ipa'), any)).thenAnswer((Invocation _) { }); when(os.unzip(fs.file('app.ipa'), any)).thenAnswer((Invocation _) { });
final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('app.ipa')); final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('app.ipa'));
expect(iosApp, isNull); expect(iosApp, isNull);
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
expect( expect(
logger.errorText, logger.errorText,
'Invalid prebuilt iOS ipa. Does not contain a "Payload" directory.\n', 'Invalid prebuilt iOS ipa. Does not contain a "Payload" directory.\n',
...@@ -251,7 +251,7 @@ void main() { ...@@ -251,7 +251,7 @@ void main() {
}); });
final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('app.ipa')); final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('app.ipa'));
expect(iosApp, isNull); expect(iosApp, isNull);
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
expect(logger.errorText, expect(logger.errorText,
'Invalid prebuilt iOS ipa. Does not contain a single app bundle.\n'); 'Invalid prebuilt iOS ipa. Does not contain a single app bundle.\n');
}, overrides: overrides); }, overrides: overrides);
...@@ -271,7 +271,7 @@ void main() { ...@@ -271,7 +271,7 @@ void main() {
.writeAsStringSync(plistData); .writeAsStringSync(plistData);
}); });
final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('app.ipa')); final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('app.ipa'));
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
expect(logger.errorText, isEmpty); expect(logger.errorText, isEmpty);
expect(iosApp.bundleDir.path, endsWith('bundle.app')); expect(iosApp.bundleDir.path, endsWith('bundle.app'));
expect(iosApp.id, 'fooBundleId'); expect(iosApp.id, 'fooBundleId');
......
...@@ -80,7 +80,7 @@ void main() { ...@@ -80,7 +80,7 @@ void main() {
await context.run<void>( await context.run<void>(
body: () { body: () {
outer.future.then<void>((_) { outer.future.then<void>((_) {
value = context[String]; value = context.get<String>();
inner.complete(); inner.complete();
}); });
}, },
...@@ -99,10 +99,10 @@ void main() { ...@@ -99,10 +99,10 @@ void main() {
String value; String value;
await context.run<void>( await context.run<void>(
body: () async { body: () async {
final StringBuffer buf = StringBuffer(context[String]); final StringBuffer buf = StringBuffer(context.get<String>());
buf.write(context[String]); buf.write(context.get<String>());
await context.run<void>(body: () { await context.run<void>(body: () {
buf.write(context[String]); buf.write(context.get<String>());
}); });
value = buf.toString(); value = buf.toString();
}, },
...@@ -122,10 +122,10 @@ void main() { ...@@ -122,10 +122,10 @@ void main() {
String value; String value;
await context.run( await context.run(
body: () async { body: () async {
final StringBuffer buf = StringBuffer(context[String]); final StringBuffer buf = StringBuffer(context.get<String>());
buf.write(context[String]); buf.write(context.get<String>());
await context.run<void>(body: () { await context.run<void>(body: () {
buf.write(context[String]); buf.write(context.get<String>());
}); });
value = buf.toString(); value = buf.toString();
}, },
...@@ -142,7 +142,7 @@ void main() { ...@@ -142,7 +142,7 @@ void main() {
test('returns null if generated value is null', () async { test('returns null if generated value is null', () async {
final String value = await context.run<String>( final String value = await context.run<String>(
body: () => context[String], body: () => context.get<String>(),
overrides: <Type, Generator>{ overrides: <Type, Generator>{
String: () => null, String: () => null,
}, },
...@@ -153,12 +153,12 @@ void main() { ...@@ -153,12 +153,12 @@ void main() {
test('throws if generator has dependency cycle', () async { test('throws if generator has dependency cycle', () async {
final Future<String> value = context.run<String>( final Future<String> value = context.run<String>(
body: () async { body: () async {
return context[String]; return context.get<String>();
}, },
fallbacks: <Type, Generator>{ fallbacks: <Type, Generator>{
int: () => int.parse(context[String]), int: () => int.parse(context.get<String>()),
String: () => '${context[double]}', String: () => '${context.get<double>()}',
double: () => (context[int] as int) * 1.0, // ignore: avoid_as double: () => context.get<int>() * 1.0,
}, },
); );
try { try {
...@@ -197,7 +197,7 @@ void main() { ...@@ -197,7 +197,7 @@ void main() {
return context.run<String>( return context.run<String>(
body: () { body: () {
called = true; called = true;
return context[String]; return context.get<String>();
}, },
fallbacks: <Type, Generator>{ fallbacks: <Type, Generator>{
String: () => 'child', String: () => 'child',
...@@ -216,7 +216,7 @@ void main() { ...@@ -216,7 +216,7 @@ void main() {
return context.run<String>( return context.run<String>(
body: () { body: () {
called = true; called = true;
return context[String]; return context.get<String>();
}, },
fallbacks: <Type, Generator>{ fallbacks: <Type, Generator>{
String: () { String: () {
...@@ -238,11 +238,11 @@ void main() { ...@@ -238,11 +238,11 @@ void main() {
test('may depend on one another', () async { test('may depend on one another', () async {
final String value = await context.run<String>( final String value = await context.run<String>(
body: () { body: () {
return context[String]; return context.get<String>();
}, },
fallbacks: <Type, Generator>{ fallbacks: <Type, Generator>{
int: () => 123, int: () => 123,
String: () => '-${context[int]}-', String: () => '-${context.get<int>()}-',
}, },
); );
expect(value, '-123-'); expect(value, '-123-');
...@@ -255,7 +255,7 @@ void main() { ...@@ -255,7 +255,7 @@ void main() {
final String value = await context.run<String>( final String value = await context.run<String>(
body: () { body: () {
return context.run<String>( return context.run<String>(
body: () => context[String], body: () => context.get<String>(),
overrides: <Type, Generator>{ overrides: <Type, Generator>{
String: () => 'child', String: () => 'child',
}, },
......
...@@ -163,7 +163,7 @@ void main() { ...@@ -163,7 +163,7 @@ void main() {
testUsingContext('Stdout startProgress on colored terminal for $testOs', () async { testUsingContext('Stdout startProgress on colored terminal for $testOs', () async {
bool done = false; bool done = false;
FakeAsync().run((FakeAsync time) { FakeAsync().run((FakeAsync time) {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
final Status status = logger.startProgress( final Status status = logger.startProgress(
'Hello', 'Hello',
progressId: null, progressId: null,
...@@ -191,7 +191,7 @@ void main() { ...@@ -191,7 +191,7 @@ void main() {
testUsingContext('Stdout startProgress on colored terminal pauses on $testOs', () async { testUsingContext('Stdout startProgress on colored terminal pauses on $testOs', () async {
bool done = false; bool done = false;
FakeAsync().run((FakeAsync time) { FakeAsync().run((FakeAsync time) {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
final Status status = logger.startProgress( final Status status = logger.startProgress(
'Knock Knock, Who\'s There', 'Knock Knock, Who\'s There',
timeout: const Duration(days: 10), timeout: const Duration(days: 10),
...@@ -368,7 +368,7 @@ void main() { ...@@ -368,7 +368,7 @@ void main() {
List<String> outputStderr() => mockStdio.writtenToStderr.join('').split('\n'); List<String> outputStderr() => mockStdio.writtenToStderr.join('').split('\n');
testUsingContext('Error logs are wrapped', () async { testUsingContext('Error logs are wrapped', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.printError('0123456789' * 15); logger.printError('0123456789' * 15);
final List<String> lines = outputStderr(); final List<String> lines = outputStderr();
expect(outputStdout().length, equals(1)); expect(outputStdout().length, equals(1));
...@@ -385,7 +385,7 @@ void main() { ...@@ -385,7 +385,7 @@ void main() {
}); });
testUsingContext('Error logs are wrapped and can be indented.', () async { testUsingContext('Error logs are wrapped and can be indented.', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.printError('0123456789' * 15, indent: 5); logger.printError('0123456789' * 15, indent: 5);
final List<String> lines = outputStderr(); final List<String> lines = outputStderr();
expect(outputStdout().length, equals(1)); expect(outputStdout().length, equals(1));
...@@ -405,7 +405,7 @@ void main() { ...@@ -405,7 +405,7 @@ void main() {
}); });
testUsingContext('Error logs are wrapped and can have hanging indent.', () async { testUsingContext('Error logs are wrapped and can have hanging indent.', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.printError('0123456789' * 15, hangingIndent: 5); logger.printError('0123456789' * 15, hangingIndent: 5);
final List<String> lines = outputStderr(); final List<String> lines = outputStderr();
expect(outputStdout().length, equals(1)); expect(outputStdout().length, equals(1));
...@@ -425,7 +425,7 @@ void main() { ...@@ -425,7 +425,7 @@ void main() {
}); });
testUsingContext('Error logs are wrapped, indented, and can have hanging indent.', () async { testUsingContext('Error logs are wrapped, indented, and can have hanging indent.', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.printError('0123456789' * 15, indent: 4, hangingIndent: 5); logger.printError('0123456789' * 15, indent: 4, hangingIndent: 5);
final List<String> lines = outputStderr(); final List<String> lines = outputStderr();
expect(outputStdout().length, equals(1)); expect(outputStdout().length, equals(1));
...@@ -445,7 +445,7 @@ void main() { ...@@ -445,7 +445,7 @@ void main() {
}); });
testUsingContext('Stdout logs are wrapped', () async { testUsingContext('Stdout logs are wrapped', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.printStatus('0123456789' * 15); logger.printStatus('0123456789' * 15);
final List<String> lines = outputStdout(); final List<String> lines = outputStdout();
expect(outputStderr().length, equals(1)); expect(outputStderr().length, equals(1));
...@@ -462,7 +462,7 @@ void main() { ...@@ -462,7 +462,7 @@ void main() {
}); });
testUsingContext('Stdout logs are wrapped and can be indented.', () async { testUsingContext('Stdout logs are wrapped and can be indented.', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.printStatus('0123456789' * 15, indent: 5); logger.printStatus('0123456789' * 15, indent: 5);
final List<String> lines = outputStdout(); final List<String> lines = outputStdout();
expect(outputStderr().length, equals(1)); expect(outputStderr().length, equals(1));
...@@ -482,7 +482,7 @@ void main() { ...@@ -482,7 +482,7 @@ void main() {
}); });
testUsingContext('Stdout logs are wrapped and can have hanging indent.', () async { testUsingContext('Stdout logs are wrapped and can have hanging indent.', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.printStatus('0123456789' * 15, hangingIndent: 5); logger.printStatus('0123456789' * 15, hangingIndent: 5);
final List<String> lines = outputStdout(); final List<String> lines = outputStdout();
expect(outputStderr().length, equals(1)); expect(outputStderr().length, equals(1));
...@@ -502,7 +502,7 @@ void main() { ...@@ -502,7 +502,7 @@ void main() {
}); });
testUsingContext('Stdout logs are wrapped, indented, and can have hanging indent.', () async { testUsingContext('Stdout logs are wrapped, indented, and can have hanging indent.', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.printStatus('0123456789' * 15, indent: 4, hangingIndent: 5); logger.printStatus('0123456789' * 15, indent: 4, hangingIndent: 5);
final List<String> lines = outputStdout(); final List<String> lines = outputStdout();
expect(outputStderr().length, equals(1)); expect(outputStderr().length, equals(1));
...@@ -522,7 +522,7 @@ void main() { ...@@ -522,7 +522,7 @@ void main() {
}); });
testUsingContext('Error logs are red', () async { testUsingContext('Error logs are red', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.printError('Pants on fire!'); logger.printError('Pants on fire!');
final List<String> lines = outputStderr(); final List<String> lines = outputStderr();
expect(outputStdout().length, equals(1)); expect(outputStdout().length, equals(1));
...@@ -536,7 +536,7 @@ void main() { ...@@ -536,7 +536,7 @@ void main() {
}); });
testUsingContext('Stdout logs are not colored', () async { testUsingContext('Stdout logs are not colored', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.printStatus('All good.'); logger.printStatus('All good.');
final List<String> lines = outputStdout(); final List<String> lines = outputStdout();
expect(outputStderr().length, equals(1)); expect(outputStderr().length, equals(1));
...@@ -549,7 +549,7 @@ void main() { ...@@ -549,7 +549,7 @@ void main() {
}); });
testUsingContext('Stdout printStatus handle null inputs on colored terminal', () async { testUsingContext('Stdout printStatus handle null inputs on colored terminal', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.printStatus( logger.printStatus(
null, null,
emphasis: null, emphasis: null,
...@@ -568,7 +568,7 @@ void main() { ...@@ -568,7 +568,7 @@ void main() {
}); });
testUsingContext('Stdout printStatus handle null inputs on non-color terminal', () async { testUsingContext('Stdout printStatus handle null inputs on non-color terminal', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.printStatus( logger.printStatus(
null, null,
emphasis: null, emphasis: null,
...@@ -590,7 +590,7 @@ void main() { ...@@ -590,7 +590,7 @@ void main() {
testUsingContext('Stdout startProgress on non-color terminal', () async { testUsingContext('Stdout startProgress on non-color terminal', () async {
bool done = false; bool done = false;
FakeAsync().run((FakeAsync time) { FakeAsync().run((FakeAsync time) {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
final Status status = logger.startProgress( final Status status = logger.startProgress(
'Hello', 'Hello',
progressId: null, progressId: null,
...@@ -661,7 +661,7 @@ void main() { ...@@ -661,7 +661,7 @@ void main() {
}, overrides: <Type, Generator>{Stdio: () => mockStdio, Platform: _kNoAnsiPlatform}); }, overrides: <Type, Generator>{Stdio: () => mockStdio, Platform: _kNoAnsiPlatform});
testUsingContext('sequential startProgress calls with StdoutLogger', () async { testUsingContext('sequential startProgress calls with StdoutLogger', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.startProgress('AAA', timeout: timeoutConfiguration.fastOperation)..stop(); logger.startProgress('AAA', timeout: timeoutConfiguration.fastOperation)..stop();
logger.startProgress('BBB', timeout: timeoutConfiguration.fastOperation)..stop(); logger.startProgress('BBB', timeout: timeoutConfiguration.fastOperation)..stop();
final List<String> output = outputStdout(); final List<String> output = outputStdout();
...@@ -679,7 +679,7 @@ void main() { ...@@ -679,7 +679,7 @@ void main() {
}); });
testUsingContext('sequential startProgress calls with VerboseLogger and StdoutLogger', () async { testUsingContext('sequential startProgress calls with VerboseLogger and StdoutLogger', () async {
final Logger logger = context[Logger]; final Logger logger = context.get<Logger>();
logger.startProgress('AAA', timeout: timeoutConfiguration.fastOperation)..stop(); logger.startProgress('AAA', timeout: timeoutConfiguration.fastOperation)..stop();
logger.startProgress('BBB', timeout: timeoutConfiguration.fastOperation)..stop(); logger.startProgress('BBB', timeout: timeoutConfiguration.fastOperation)..stop();
expect(outputStdout(), <Matcher>[ expect(outputStdout(), <Matcher>[
...@@ -696,7 +696,7 @@ void main() { ...@@ -696,7 +696,7 @@ void main() {
}); });
testUsingContext('sequential startProgress calls with BufferLogger', () async { testUsingContext('sequential startProgress calls with BufferLogger', () async {
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
logger.startProgress('AAA', timeout: timeoutConfiguration.fastOperation)..stop(); logger.startProgress('AAA', timeout: timeoutConfiguration.fastOperation)..stop();
logger.startProgress('BBB', timeout: timeoutConfiguration.fastOperation)..stop(); logger.startProgress('BBB', timeout: timeoutConfiguration.fastOperation)..stop();
expect(logger.statusText, 'AAA\nBBB\n'); expect(logger.statusText, 'AAA\nBBB\n');
......
...@@ -25,7 +25,7 @@ void main() { ...@@ -25,7 +25,7 @@ void main() {
group('config', () { group('config', () {
testUsingContext('machine flag', () async { testUsingContext('machine flag', () async {
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
final ConfigCommand command = ConfigCommand(); final ConfigCommand command = ConfigCommand();
await command.handleMachine(); await command.handleMachine();
......
...@@ -114,7 +114,7 @@ example:org-dartlang-app:/ ...@@ -114,7 +114,7 @@ example:org-dartlang-app:/
}); });
testUsingContext('single dart successful compilation', () async { testUsingContext('single dart successful compilation', () async {
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
when(mockFrontendServer.stdout) when(mockFrontendServer.stdout)
.thenAnswer((Invocation invocation) => Stream<List<int>>.fromFuture( .thenAnswer((Invocation invocation) => Stream<List<int>>.fromFuture(
Future<List<int>>.value(utf8.encode( Future<List<int>>.value(utf8.encode(
...@@ -137,7 +137,7 @@ example:org-dartlang-app:/ ...@@ -137,7 +137,7 @@ example:org-dartlang-app:/
}); });
testUsingContext('single dart failed compilation', () async { testUsingContext('single dart failed compilation', () async {
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
when(mockFrontendServer.stdout) when(mockFrontendServer.stdout)
.thenAnswer((Invocation invocation) => Stream<List<int>>.fromFuture( .thenAnswer((Invocation invocation) => Stream<List<int>>.fromFuture(
...@@ -163,7 +163,7 @@ example:org-dartlang-app:/ ...@@ -163,7 +163,7 @@ example:org-dartlang-app:/
testUsingContext('single dart abnormal compiler termination', () async { testUsingContext('single dart abnormal compiler termination', () async {
when(mockFrontendServer.exitCode).thenAnswer((_) async => 255); when(mockFrontendServer.exitCode).thenAnswer((_) async => 255);
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
when(mockFrontendServer.stdout) when(mockFrontendServer.stdout)
.thenAnswer((Invocation invocation) => Stream<List<int>>.fromFuture( .thenAnswer((Invocation invocation) => Stream<List<int>>.fromFuture(
...@@ -221,7 +221,7 @@ example:org-dartlang-app:/ ...@@ -221,7 +221,7 @@ example:org-dartlang-app:/
}); });
testUsingContext('single dart compile', () async { testUsingContext('single dart compile', () async {
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
when(mockFrontendServer.stdout) when(mockFrontendServer.stdout)
.thenAnswer((Invocation invocation) => Stream<List<int>>.fromFuture( .thenAnswer((Invocation invocation) => Stream<List<int>>.fromFuture(
...@@ -265,7 +265,7 @@ example:org-dartlang-app:/ ...@@ -265,7 +265,7 @@ example:org-dartlang-app:/
}); });
testUsingContext('compile and recompile', () async { testUsingContext('compile and recompile', () async {
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
final StreamController<List<int>> streamController = StreamController<List<int>>(); final StreamController<List<int>> streamController = StreamController<List<int>>();
when(mockFrontendServer.stdout) when(mockFrontendServer.stdout)
...@@ -309,7 +309,7 @@ example:org-dartlang-app:/ ...@@ -309,7 +309,7 @@ example:org-dartlang-app:/
}); });
testUsingContext('compile and recompile twice', () async { testUsingContext('compile and recompile twice', () async {
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
final StreamController<List<int>> streamController = StreamController<List<int>>(); final StreamController<List<int>> streamController = StreamController<List<int>>();
when(mockFrontendServer.stdout) when(mockFrontendServer.stdout)
...@@ -380,7 +380,7 @@ example:org-dartlang-app:/ ...@@ -380,7 +380,7 @@ example:org-dartlang-app:/
}); });
testUsingContext('compile single expression', () async { testUsingContext('compile single expression', () async {
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
final Completer<List<int>> compileResponseCompleter = final Completer<List<int>> compileResponseCompleter =
Completer<List<int>>(); Completer<List<int>>();
...@@ -432,7 +432,7 @@ example:org-dartlang-app:/ ...@@ -432,7 +432,7 @@ example:org-dartlang-app:/
}); });
testUsingContext('compile expressions without awaiting', () async { testUsingContext('compile expressions without awaiting', () async {
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
final Completer<List<int>> compileResponseCompleter = Completer<List<int>>(); final Completer<List<int>> compileResponseCompleter = Completer<List<int>>();
final Completer<List<int>> compileExpressionResponseCompleter1 = Completer<List<int>>(); final Completer<List<int>> compileExpressionResponseCompleter1 = Completer<List<int>>();
......
...@@ -109,7 +109,7 @@ void main() { ...@@ -109,7 +109,7 @@ void main() {
expect(fields['error_runtime_type'], 'StateError'); expect(fields['error_runtime_type'], 'StateError');
expect(fields['error_message'], 'Bad state: Test bad state error'); expect(fields['error_message'], 'Bad state: Test bad state error');
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
expect(logger.statusText, 'Sending crash report to Google.\n' expect(logger.statusText, 'Sending crash report to Google.\n'
'Crash report sent (report ID: test-report-id)\n'); 'Crash report sent (report ID: test-report-id)\n');
......
...@@ -27,7 +27,7 @@ void main() { ...@@ -27,7 +27,7 @@ void main() {
testUsingContext('pub get 69', () async { testUsingContext('pub get 69', () async {
String error; String error;
final MockProcessManager processMock = context[ProcessManager]; final MockProcessManager processMock = context.get<ProcessManager>();
FakeAsync().run((FakeAsync time) { FakeAsync().run((FakeAsync time) {
expect(processMock.lastPubEnvironment, isNull); expect(processMock.lastPubEnvironment, isNull);
...@@ -95,8 +95,8 @@ void main() { ...@@ -95,8 +95,8 @@ void main() {
testUsingContext('pub cache in root is used', () async { testUsingContext('pub cache in root is used', () async {
String error; String error;
final MockProcessManager processMock = context[ProcessManager]; final MockProcessManager processMock = context.get<ProcessManager>() as MockProcessManager;
final MockFileSystem fsMock = context[FileSystem]; final MockFileSystem fsMock = context.get<FileSystem>() as MockFileSystem;
FakeAsync().run((FakeAsync time) { FakeAsync().run((FakeAsync time) {
MockDirectory.findCache = true; MockDirectory.findCache = true;
...@@ -122,7 +122,7 @@ void main() { ...@@ -122,7 +122,7 @@ void main() {
testUsingContext('pub cache in environment is used', () async { testUsingContext('pub cache in environment is used', () async {
String error; String error;
final MockProcessManager processMock = context[ProcessManager]; final MockProcessManager processMock = context.get<ProcessManager>();
FakeAsync().run((FakeAsync time) { FakeAsync().run((FakeAsync time) {
MockDirectory.findCache = true; MockDirectory.findCache = true;
......
...@@ -30,10 +30,10 @@ import 'common.dart'; ...@@ -30,10 +30,10 @@ import 'common.dart';
export 'package:flutter_tools/src/base/context.dart' show Generator; export 'package:flutter_tools/src/base/context.dart' show Generator;
/// Return the test logger. This assumes that the current Logger is a BufferLogger. /// Return the test logger. This assumes that the current Logger is a BufferLogger.
BufferLogger get testLogger => context[Logger]; BufferLogger get testLogger => context.get<Logger>();
MockDeviceManager get testDeviceManager => context[DeviceManager]; MockDeviceManager get testDeviceManager => context.get<DeviceManager>();
MockDoctor get testDoctor => context[Doctor]; MockDoctor get testDoctor => context.get<Doctor>();
typedef ContextInitializer = void Function(AppContext testContext); typedef ContextInitializer = void Function(AppContext testContext);
...@@ -126,8 +126,8 @@ void testUsingContext( ...@@ -126,8 +126,8 @@ void testUsingContext(
} }
void _printBufferedErrors(AppContext testContext) { void _printBufferedErrors(AppContext testContext) {
if (testContext[Logger] is BufferLogger) { if (testContext.get<Logger>() is BufferLogger) {
final BufferLogger bufferLogger = testContext[Logger]; final BufferLogger bufferLogger = testContext.get<Logger>();
if (bufferLogger.errorText.isNotEmpty) if (bufferLogger.errorText.isNotEmpty)
print(bufferLogger.errorText); print(bufferLogger.errorText);
bufferLogger.clear(); bufferLogger.clear();
......
...@@ -414,7 +414,7 @@ void main() { ...@@ -414,7 +414,7 @@ void main() {
} }
void _expectVersionMessage(String message) { void _expectVersionMessage(String message) {
final BufferLogger logger = context[Logger]; final BufferLogger logger = context.get<Logger>();
expect(logger.statusText.trim(), message.trim()); expect(logger.statusText.trim(), message.trim());
logger.clear(); logger.clear();
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment