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

This commit is contained in:
Jonah Williams 2019-04-25 15:51:08 -07:00 committed by GitHub
parent 0e5d771a2a
commit 0acd3e6b04
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
56 changed files with 144 additions and 127 deletions

View file

@ -3,6 +3,12 @@
include: ../../analysis_options.yaml
analyzer:
strong-mode:
implicit-casts: true
implicit-dynamic: false
linter:
rules:
- unawaited_futures
unawaited_futures: true
avoid_as: false # Disabled so we can gradually migrate to no implicit dynamic.

View file

@ -17,7 +17,7 @@ import '../convert.dart';
import '../globals.dart';
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 kAndroidSdkRoot = 'ANDROID_SDK_ROOT';

View file

@ -13,7 +13,7 @@ import '../globals.dart';
import '../ios/ios_workflow.dart';
import '../ios/plist_utils.dart' as plist;
AndroidStudio get androidStudio => context[AndroidStudio];
AndroidStudio get androidStudio => context.get<AndroidStudio>();
// Android Studio layout:

View file

@ -21,9 +21,9 @@ import 'android_sdk.dart';
const int kAndroidSdkMinVersion = 28;
final Version kAndroidSdkBuildToolsMinVersion = Version(28, 0, 3);
AndroidWorkflow get androidWorkflow => context[AndroidWorkflow];
AndroidValidator get androidValidator => context[AndroidValidator];
AndroidLicenseValidator get androidLicenseValidator => context[AndroidLicenseValidator];
AndroidWorkflow get androidWorkflow => context.get<AndroidWorkflow>();
AndroidValidator get androidValidator => context.get<AndroidValidator>();
AndroidLicenseValidator get androidLicenseValidator => context.get<AndroidLicenseValidator>();
enum LicensesAccepted {
none,

View file

@ -28,7 +28,7 @@ import 'web/web_device.dart';
import 'windows/application_package.dart';
class ApplicationPackageFactory {
static ApplicationPackageFactory get instance => context[ApplicationPackageFactory];
static ApplicationPackageFactory get instance => context.get<ApplicationPackageFactory>();
Future<ApplicationPackage> getPackageForPlatform(
TargetPlatform platform, {

View file

@ -100,7 +100,7 @@ class EngineBuildPaths {
// Manages the engine artifacts of Flutter.
abstract class Artifacts {
static Artifacts get instance => context[Artifacts];
static Artifacts get instance => context.get<Artifacts>();
static LocalEngineArtifacts getLocalEngine(String engineSrcPath, EngineBuildPaths engineBuildPaths) {
return LocalEngineArtifacts(engineSrcPath, engineBuildPaths.targetEngine, engineBuildPaths.hostEngine);

View file

@ -23,7 +23,7 @@ const AssetBundleFactory _kManifestFactory = _ManifestAssetBundleFactory();
/// Injected factory class for spawning [AssetBundle] instances.
abstract class AssetBundleFactory {
/// 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;

View file

@ -21,7 +21,7 @@ import 'file_system.dart';
import 'fingerprint.dart';
import 'process.dart';
GenSnapshot get genSnapshot => context[GenSnapshot];
GenSnapshot get genSnapshot => context.get<GenSnapshot>();
/// A snapshot build configuration.
class SnapshotType {

View file

@ -14,7 +14,7 @@ class Config {
_values = json.decode(_configFile.readAsStringSync());
}
static Config get instance => context[Config];
static Config get instance => context.get<Config>();
File _configFile;
String get configPath => _configFile.path;

View file

@ -33,7 +33,7 @@ class ContextDependencyCycleException implements Exception {
/// context will not have any values associated with it.
///
/// 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
/// code is run.
@ -107,6 +107,17 @@ class AppContext {
/// Gets the value associated with the specified [type], or `null` if no
/// 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) {
dynamic value = _generateIfNecessary(type, _overrides);
if (value == null && _parent != null)

View file

@ -23,7 +23,7 @@ const FileSystem _kLocalFs = LocalFileSystem();
///
/// By default it uses local disk-based implementation. Override this in tests
/// 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
/// base recording [location].

View file

@ -8,7 +8,7 @@ import 'context.dart';
/// command-line flags and options that were specified during the invocation of
/// 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
/// during the invocation of the Flutter tool.

View file

@ -163,7 +163,7 @@ class Stdio {
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;
Stream<List<int>> get stdin => stdio.stdin;
io.IOSink get stderr => stdio.stderr;

View file

@ -19,7 +19,7 @@ const Duration _kSlowOperation = Duration(minutes: 2);
/// The [TimeoutConfiguration] instance.
///
/// 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 {
const TimeoutConfiguration();
@ -486,7 +486,7 @@ abstract class Status {
final VoidCallback onFinish;
@protected
final Stopwatch _stopwatch = context[Stopwatch] ?? Stopwatch();
final Stopwatch _stopwatch = context.get<Stopwatch>() ?? Stopwatch();
@protected
@visibleForTesting

View file

@ -36,8 +36,8 @@ Future<bool> doesRemoteFileExist(Uri url) async =>
Future<List<int>> _attempt(Uri url, { bool onlyHeaders = false }) async {
printTrace('Downloading: $url');
HttpClient httpClient;
if (context[HttpClientFactory] != null) {
httpClient = (context[HttpClientFactory] as HttpClientFactory)(); // ignore: avoid_as
if (context.get<HttpClientFactory>() != null) {
httpClient = context.get<HttpClientFactory>()();
} else {
httpClient = HttpClient();
}

View file

@ -11,7 +11,7 @@ import 'process.dart';
import 'process_manager.dart';
/// 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 {
factory OperatingSystemUtils() {

View file

@ -14,7 +14,7 @@ export 'package:platform/platform.dart';
const Platform _kLocalPlatform = LocalPlatform();
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
/// [location].

View file

@ -16,7 +16,7 @@ const String _kRecordingType = 'process';
const ProcessManager _kLocalProcessManager = LocalProcessManager();
/// 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
/// specified base recording [location].

View file

@ -14,9 +14,9 @@ import 'utils.dart';
final AnsiTerminal _kAnsiTerminal = AnsiTerminal();
AnsiTerminal get terminal {
return (context == null || context[AnsiTerminal] == null)
return (context == null || context.get<AnsiTerminal>() == null)
? _kAnsiTerminal
: context[AnsiTerminal];
: context.get<AnsiTerminal>();
}
enum TerminalColor {
@ -31,9 +31,9 @@ enum TerminalColor {
final OutputPreferences _kOutputPreferences = OutputPreferences();
OutputPreferences get outputPreferences => (context == null || context[OutputPreferences] == null)
OutputPreferences get outputPreferences => (context == null || context.get<OutputPreferences>() == null)
? _kOutputPreferences
: context[OutputPreferences];
: context.get<OutputPreferences>();
/// A class that contains the context settings for command text output to the
/// console.

View file

@ -5,7 +5,7 @@
import 'context.dart';
/// The current system clock instance.
SystemClock get systemClock => context[SystemClock];
SystemClock get systemClock => context.get<SystemClock>();
/// A class for making time based operations testable.
class SystemClock {

View file

@ -4,7 +4,7 @@
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 UserMessages {

View file

@ -49,7 +49,7 @@ class BotDetector {
}
bool get isRunningOnBot {
final BotDetector botDetector = context[BotDetector] ?? _kBotDetector;
final BotDetector botDetector = context.get<BotDetector>() ?? _kBotDetector;
return botDetector.isRunningOnBot;
}

View file

@ -197,7 +197,7 @@ class Cache {
}
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`.
Directory getRoot() {

View file

@ -22,7 +22,7 @@ const String kMultiRootScheme = 'org-dartlang-app';
///
/// If [experimentalBuildEnabled] is false, this will contain an unsupported
/// implementation.
CodeGenerator get codeGenerator => context[CodeGenerator];
CodeGenerator get codeGenerator => context.get<CodeGenerator>();
/// A wrapper for a build_runner process which delegates to a generated
/// build script.

View file

@ -23,7 +23,7 @@ import 'dart/package_map.dart';
import 'globals.dart';
import 'project.dart';
KernelCompilerFactory get kernelCompilerFactory => context[KernelCompilerFactory];
KernelCompilerFactory get kernelCompilerFactory => context.get<KernelCompilerFactory>();
class KernelCompilerFactory {
const KernelCompilerFactory();

View file

@ -26,7 +26,7 @@ class DevFSConfig {
bool noDirectorySymlinks = false;
}
DevFSConfig get devFSConfig => context[DevFSConfig];
DevFSConfig get devFSConfig => context.get<DevFSConfig>();
/// Common superclass for content copied to the device.
abstract class DevFSContent {

View file

@ -24,7 +24,7 @@ import 'tester/flutter_tester.dart';
import 'web/web_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.
class DeviceManager {

View file

@ -33,11 +33,11 @@ import 'version.dart';
import 'vscode/vscode_validator.dart';
import 'windows/windows_workflow.dart';
Doctor get doctor => context[Doctor];
Doctor get doctor => context.get<Doctor>();
abstract class DoctorValidatorsProvider {
/// 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();

View file

@ -13,7 +13,7 @@ import 'base/process_manager.dart';
import 'globals.dart';
import 'ios/ios_emulators.dart';
EmulatorManager get emulatorManager => context[EmulatorManager];
EmulatorManager get emulatorManager => context.get<EmulatorManager>();
/// A class to get all available emulators.
class EmulatorManager {

View file

@ -13,10 +13,10 @@ import '../convert.dart';
import '../globals.dart';
/// The [FuchsiaSdk] instance.
FuchsiaSdk get fuchsiaSdk => context[FuchsiaSdk];
FuchsiaSdk get fuchsiaSdk => context.get<FuchsiaSdk>();
/// The [FuchsiaArtifacts] instance.
FuchsiaArtifacts get fuchsiaArtifacts => context[FuchsiaArtifacts];
FuchsiaArtifacts get fuchsiaArtifacts => context.get<FuchsiaArtifacts>();
/// The Fuchsia SDK shell commands.
///

View file

@ -8,7 +8,7 @@ import '../doctor.dart';
import 'fuchsia_sdk.dart';
/// The [FuchsiaWorkflow] instance.
FuchsiaWorkflow get fuchsiaWorkflow => context[FuchsiaWorkflow];
FuchsiaWorkflow get fuchsiaWorkflow => context.get<FuchsiaWorkflow>();
/// The Fuchsia-specific implementation of a [Workflow].
///

View file

@ -9,7 +9,7 @@ import 'base/logger.dart';
import 'base/terminal.dart';
import 'cache.dart';
Logger get logger => context[Logger];
Logger get logger => context.get<Logger>();
Cache get cache => Cache.instance;
Config get config => Config.instance;
Artifacts get artifacts => Artifacts.instance;

View file

@ -37,7 +37,7 @@ const String cocoaPodsUpgradeInstructions = '''
brew upgrade cocoapods
pod setup''';
CocoaPods get cocoaPods => context[CocoaPods];
CocoaPods get cocoaPods => context.get<CocoaPods>();
/// Result of evaluating the CocoaPods installation.
enum CocoaPodsStatus {

View file

@ -15,9 +15,9 @@ import 'cocoapods.dart';
import 'mac.dart';
import 'plist_utils.dart' as plist;
IOSWorkflow get iosWorkflow => context[IOSWorkflow];
IOSValidator get iosValidator => context[IOSValidator];
CocoaPodsValidator get cocoapodsValidator => context[CocoaPodsValidator];
IOSWorkflow get iosWorkflow => context.get<IOSWorkflow>();
IOSValidator get iosValidator => context.get<IOSValidator>();
CocoaPodsValidator get cocoapodsValidator => context.get<CocoaPodsValidator>();
class IOSWorkflow implements Workflow {
const IOSWorkflow();

View file

@ -31,9 +31,9 @@ import 'xcodeproj.dart';
const int kXcodeRequiredVersionMajor = 9;
const int kXcodeRequiredVersionMinor = 0;
IMobileDevice get iMobileDevice => context[IMobileDevice];
PlistBuddy get plistBuddy => context[PlistBuddy];
Xcode get xcode => context[Xcode];
IMobileDevice get iMobileDevice => context.get<IMobileDevice>();
PlistBuddy get plistBuddy => context.get<PlistBuddy>();
Xcode get xcode => context.get<Xcode>();
class PlistBuddy {
const PlistBuddy();

View file

@ -41,7 +41,7 @@ class IOSSimulators extends PollingDeviceDiscovery {
class IOSSimulatorUtils {
/// 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() {
if (!xcode.isInstalledAndMeetsVersionCheck)
@ -56,7 +56,7 @@ class IOSSimulatorUtils {
/// A wrapper around the `simctl` command line tool.
class SimControl {
/// 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
/// [section].

View file

@ -127,7 +127,7 @@ Future<void> updateGeneratedXcodeProperties({
generatedXcodePropertiesFile.writeAsStringSync(localsBuffer.toString());
}
XcodeProjectInterpreter get xcodeProjectInterpreter => context[XcodeProjectInterpreter];
XcodeProjectInterpreter get xcodeProjectInterpreter => context.get<XcodeProjectInterpreter>();
/// Interpreter of Xcode projects.
class XcodeProjectInterpreter {

View file

@ -8,7 +8,7 @@ import '../desktop.dart';
import '../doctor.dart';
/// The [WindowsWorkflow] instance.
LinuxWorkflow get linuxWorkflow => context[LinuxWorkflow];
LinuxWorkflow get linuxWorkflow => context.get<LinuxWorkflow>();
/// The windows-specific implementation of a [Workflow].
///

View file

@ -8,7 +8,7 @@ import '../desktop.dart';
import '../doctor.dart';
/// The [MacOSWorkflow] instance.
MacOSWorkflow get macOSWorkflow => context[MacOSWorkflow];
MacOSWorkflow get macOSWorkflow => context.get<MacOSWorkflow>();
/// The macOS-specific implementation of a [Workflow].
///

View file

@ -40,7 +40,7 @@ class HotRunnerConfig {
}
}
HotRunnerConfig get hotRunnerConfig => context[HotRunnerConfig];
HotRunnerConfig get hotRunnerConfig => context.get<HotRunnerConfig>();
const bool kHotReloadDefault = true;

View file

@ -77,7 +77,7 @@ abstract class FlutterCommand extends Command<void> {
/// The currently executing command (or sub-command).
///
/// 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.
static const String observatoryPortOption = 'observatory-port';

View file

@ -55,7 +55,7 @@ class Usage {
}
/// Returns [Usage] active in the current app context.
static Usage get instance => context[Usage];
static Usage get instance => context.get<Usage>();
Analytics _analytics;

View file

@ -179,7 +179,7 @@ class FlutterVersion {
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`).
String getVersionString({ bool redactUnknownBranches = false }) {

View file

@ -82,7 +82,7 @@ Future<StreamChannel<String>> _defaultOpenChannel(Uri uri, {io.CompressionOption
delay *= 2;
}
final WebSocketConnector constructor = context[WebSocketConnector] ?? io.WebSocket.connect;
final WebSocketConnector constructor = context.get<WebSocketConnector>() ?? io.WebSocket.connect;
while (socket == null) {
attempts += 1;
try {

View file

@ -15,7 +15,7 @@ import '../convert.dart';
import '../globals.dart';
/// The [WebCompiler] instance.
WebCompiler get webCompiler => context[WebCompiler];
WebCompiler get webCompiler => context.get<WebCompiler>();
/// A wrapper around dart2js for web compilation.
class WebCompiler {

View file

@ -16,7 +16,7 @@ import '../project.dart';
import '../version.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`
/// environment variable is set to true.

View file

@ -8,7 +8,7 @@ import '../desktop.dart';
import '../doctor.dart';
/// The [WindowsWorkflow] instance.
WindowsWorkflow get windowsWorkflow => context[WindowsWorkflow];
WindowsWorkflow get windowsWorkflow => context.get<WindowsWorkflow>();
/// The windows-specific implementation of a [Workflow].
///

View file

@ -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', () {
final ApkManifestData data = ApkManifestData.parseFromXmlDump(_aaptDataWithNoEnabledActivity);
expect(data, isNull);
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
expect(
logger.errorText, 'Error running io.flutter.examples.hello_world. Default activity not found\n');
}, overrides: noColorTerminalOverride);
testUsingContext('Error when parsing manifest with no Activity that has action set to android.intent.action.MAIN', () {
final ApkManifestData data = ApkManifestData.parseFromXmlDump(_aaptDataWithNoMainActivity);
expect(data, isNull);
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
expect(
logger.errorText, 'Error running io.flutter.examples.hello_world. Default activity not found\n');
}, overrides: noColorTerminalOverride);
testUsingContext('Error when parsing manifest with no Activity that has category set to android.intent.category.LAUNCHER', () {
final ApkManifestData data = ApkManifestData.parseFromXmlDump(_aaptDataWithNoLauncherActivity);
expect(data, isNull);
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
expect(
logger.errorText, 'Error running io.flutter.examples.hello_world. Default activity not found\n');
}, overrides: noColorTerminalOverride);
@ -176,7 +176,7 @@ void main() {
final PrebuiltIOSApp iosApp =
IOSApp.fromPrebuiltApp(fs.file('not_existing.ipa'));
expect(iosApp, isNull);
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
expect(
logger.errorText,
'File "not_existing.ipa" does not exist. Use an app bundle or an ipa.\n',
@ -187,7 +187,7 @@ void main() {
final PrebuiltIOSApp iosApp =
IOSApp.fromPrebuiltApp(fs.file('regular_folder'));
expect(iosApp, isNull);
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
expect(
logger.errorText, 'Folder "regular_folder" is not an app bundle.\n');
}, overrides: overrides);
@ -195,7 +195,7 @@ void main() {
fs.directory('bundle.app').createSync();
final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('bundle.app'));
expect(iosApp, isNull);
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
expect(
logger.errorText,
'Invalid prebuilt iOS app. Does not contain Info.plist.\n',
@ -206,7 +206,7 @@ void main() {
fs.file('bundle.app/Info.plist').writeAsStringSync(badPlistData);
final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('bundle.app'));
expect(iosApp, isNull);
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
expect(
logger.errorText,
contains(
@ -217,7 +217,7 @@ void main() {
fs.directory('bundle.app').createSync();
fs.file('bundle.app/Info.plist').writeAsStringSync(plistData);
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(iosApp.bundleDir.path, 'bundle.app');
expect(iosApp.id, 'fooBundleId');
@ -228,7 +228,7 @@ void main() {
when(os.unzip(fs.file('app.ipa'), any)).thenAnswer((Invocation _) { });
final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('app.ipa'));
expect(iosApp, isNull);
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
expect(
logger.errorText,
'Invalid prebuilt iOS ipa. Does not contain a "Payload" directory.\n',
@ -251,7 +251,7 @@ void main() {
});
final PrebuiltIOSApp iosApp = IOSApp.fromPrebuiltApp(fs.file('app.ipa'));
expect(iosApp, isNull);
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
expect(logger.errorText,
'Invalid prebuilt iOS ipa. Does not contain a single app bundle.\n');
}, overrides: overrides);
@ -271,7 +271,7 @@ void main() {
.writeAsStringSync(plistData);
});
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(iosApp.bundleDir.path, endsWith('bundle.app'));
expect(iosApp.id, 'fooBundleId');

View file

@ -80,7 +80,7 @@ void main() {
await context.run<void>(
body: () {
outer.future.then<void>((_) {
value = context[String];
value = context.get<String>();
inner.complete();
});
},
@ -99,10 +99,10 @@ void main() {
String value;
await context.run<void>(
body: () async {
final StringBuffer buf = StringBuffer(context[String]);
buf.write(context[String]);
final StringBuffer buf = StringBuffer(context.get<String>());
buf.write(context.get<String>());
await context.run<void>(body: () {
buf.write(context[String]);
buf.write(context.get<String>());
});
value = buf.toString();
},
@ -122,10 +122,10 @@ void main() {
String value;
await context.run(
body: () async {
final StringBuffer buf = StringBuffer(context[String]);
buf.write(context[String]);
final StringBuffer buf = StringBuffer(context.get<String>());
buf.write(context.get<String>());
await context.run<void>(body: () {
buf.write(context[String]);
buf.write(context.get<String>());
});
value = buf.toString();
},
@ -142,7 +142,7 @@ void main() {
test('returns null if generated value is null', () async {
final String value = await context.run<String>(
body: () => context[String],
body: () => context.get<String>(),
overrides: <Type, Generator>{
String: () => null,
},
@ -153,12 +153,12 @@ void main() {
test('throws if generator has dependency cycle', () async {
final Future<String> value = context.run<String>(
body: () async {
return context[String];
return context.get<String>();
},
fallbacks: <Type, Generator>{
int: () => int.parse(context[String]),
String: () => '${context[double]}',
double: () => (context[int] as int) * 1.0, // ignore: avoid_as
int: () => int.parse(context.get<String>()),
String: () => '${context.get<double>()}',
double: () => context.get<int>() * 1.0,
},
);
try {
@ -197,7 +197,7 @@ void main() {
return context.run<String>(
body: () {
called = true;
return context[String];
return context.get<String>();
},
fallbacks: <Type, Generator>{
String: () => 'child',
@ -216,7 +216,7 @@ void main() {
return context.run<String>(
body: () {
called = true;
return context[String];
return context.get<String>();
},
fallbacks: <Type, Generator>{
String: () {
@ -238,11 +238,11 @@ void main() {
test('may depend on one another', () async {
final String value = await context.run<String>(
body: () {
return context[String];
return context.get<String>();
},
fallbacks: <Type, Generator>{
int: () => 123,
String: () => '-${context[int]}-',
String: () => '-${context.get<int>()}-',
},
);
expect(value, '-123-');
@ -255,7 +255,7 @@ void main() {
final String value = await context.run<String>(
body: () {
return context.run<String>(
body: () => context[String],
body: () => context.get<String>(),
overrides: <Type, Generator>{
String: () => 'child',
},

View file

@ -163,7 +163,7 @@ void main() {
testUsingContext('Stdout startProgress on colored terminal for $testOs', () async {
bool done = false;
FakeAsync().run((FakeAsync time) {
final Logger logger = context[Logger];
final Logger logger = context.get<Logger>();
final Status status = logger.startProgress(
'Hello',
progressId: null,
@ -191,7 +191,7 @@ void main() {
testUsingContext('Stdout startProgress on colored terminal pauses on $testOs', () async {
bool done = false;
FakeAsync().run((FakeAsync time) {
final Logger logger = context[Logger];
final Logger logger = context.get<Logger>();
final Status status = logger.startProgress(
'Knock Knock, Who\'s There',
timeout: const Duration(days: 10),
@ -368,7 +368,7 @@ void main() {
List<String> outputStderr() => mockStdio.writtenToStderr.join('').split('\n');
testUsingContext('Error logs are wrapped', () async {
final Logger logger = context[Logger];
final Logger logger = context.get<Logger>();
logger.printError('0123456789' * 15);
final List<String> lines = outputStderr();
expect(outputStdout().length, equals(1));
@ -385,7 +385,7 @@ void main() {
});
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);
final List<String> lines = outputStderr();
expect(outputStdout().length, equals(1));
@ -405,7 +405,7 @@ void main() {
});
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);
final List<String> lines = outputStderr();
expect(outputStdout().length, equals(1));
@ -425,7 +425,7 @@ void main() {
});
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);
final List<String> lines = outputStderr();
expect(outputStdout().length, equals(1));
@ -445,7 +445,7 @@ void main() {
});
testUsingContext('Stdout logs are wrapped', () async {
final Logger logger = context[Logger];
final Logger logger = context.get<Logger>();
logger.printStatus('0123456789' * 15);
final List<String> lines = outputStdout();
expect(outputStderr().length, equals(1));
@ -462,7 +462,7 @@ void main() {
});
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);
final List<String> lines = outputStdout();
expect(outputStderr().length, equals(1));
@ -482,7 +482,7 @@ void main() {
});
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);
final List<String> lines = outputStdout();
expect(outputStderr().length, equals(1));
@ -502,7 +502,7 @@ void main() {
});
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);
final List<String> lines = outputStdout();
expect(outputStderr().length, equals(1));
@ -522,7 +522,7 @@ void main() {
});
testUsingContext('Error logs are red', () async {
final Logger logger = context[Logger];
final Logger logger = context.get<Logger>();
logger.printError('Pants on fire!');
final List<String> lines = outputStderr();
expect(outputStdout().length, equals(1));
@ -536,7 +536,7 @@ void main() {
});
testUsingContext('Stdout logs are not colored', () async {
final Logger logger = context[Logger];
final Logger logger = context.get<Logger>();
logger.printStatus('All good.');
final List<String> lines = outputStdout();
expect(outputStderr().length, equals(1));
@ -549,7 +549,7 @@ void main() {
});
testUsingContext('Stdout printStatus handle null inputs on colored terminal', () async {
final Logger logger = context[Logger];
final Logger logger = context.get<Logger>();
logger.printStatus(
null,
emphasis: null,
@ -568,7 +568,7 @@ void main() {
});
testUsingContext('Stdout printStatus handle null inputs on non-color terminal', () async {
final Logger logger = context[Logger];
final Logger logger = context.get<Logger>();
logger.printStatus(
null,
emphasis: null,
@ -590,7 +590,7 @@ void main() {
testUsingContext('Stdout startProgress on non-color terminal', () async {
bool done = false;
FakeAsync().run((FakeAsync time) {
final Logger logger = context[Logger];
final Logger logger = context.get<Logger>();
final Status status = logger.startProgress(
'Hello',
progressId: null,
@ -661,7 +661,7 @@ void main() {
}, overrides: <Type, Generator>{Stdio: () => mockStdio, Platform: _kNoAnsiPlatform});
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('BBB', timeout: timeoutConfiguration.fastOperation)..stop();
final List<String> output = outputStdout();
@ -679,7 +679,7 @@ void main() {
});
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('BBB', timeout: timeoutConfiguration.fastOperation)..stop();
expect(outputStdout(), <Matcher>[
@ -696,7 +696,7 @@ void main() {
});
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('BBB', timeout: timeoutConfiguration.fastOperation)..stop();
expect(logger.statusText, 'AAA\nBBB\n');

View file

@ -25,7 +25,7 @@ void main() {
group('config', () {
testUsingContext('machine flag', () async {
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
final ConfigCommand command = ConfigCommand();
await command.handleMachine();

View file

@ -114,7 +114,7 @@ example:org-dartlang-app:/
});
testUsingContext('single dart successful compilation', () async {
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
when(mockFrontendServer.stdout)
.thenAnswer((Invocation invocation) => Stream<List<int>>.fromFuture(
Future<List<int>>.value(utf8.encode(
@ -137,7 +137,7 @@ example:org-dartlang-app:/
});
testUsingContext('single dart failed compilation', () async {
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
when(mockFrontendServer.stdout)
.thenAnswer((Invocation invocation) => Stream<List<int>>.fromFuture(
@ -163,7 +163,7 @@ example:org-dartlang-app:/
testUsingContext('single dart abnormal compiler termination', () async {
when(mockFrontendServer.exitCode).thenAnswer((_) async => 255);
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
when(mockFrontendServer.stdout)
.thenAnswer((Invocation invocation) => Stream<List<int>>.fromFuture(
@ -221,7 +221,7 @@ example:org-dartlang-app:/
});
testUsingContext('single dart compile', () async {
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
when(mockFrontendServer.stdout)
.thenAnswer((Invocation invocation) => Stream<List<int>>.fromFuture(
@ -265,7 +265,7 @@ example:org-dartlang-app:/
});
testUsingContext('compile and recompile', () async {
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
final StreamController<List<int>> streamController = StreamController<List<int>>();
when(mockFrontendServer.stdout)
@ -309,7 +309,7 @@ example:org-dartlang-app:/
});
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>>();
when(mockFrontendServer.stdout)
@ -380,7 +380,7 @@ example:org-dartlang-app:/
});
testUsingContext('compile single expression', () async {
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
final Completer<List<int>> compileResponseCompleter =
Completer<List<int>>();
@ -432,7 +432,7 @@ example:org-dartlang-app:/
});
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>> compileExpressionResponseCompleter1 = Completer<List<int>>();

View file

@ -109,7 +109,7 @@ void main() {
expect(fields['error_runtime_type'], 'StateError');
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'
'Crash report sent (report ID: test-report-id)\n');

View file

@ -27,7 +27,7 @@ void main() {
testUsingContext('pub get 69', () async {
String error;
final MockProcessManager processMock = context[ProcessManager];
final MockProcessManager processMock = context.get<ProcessManager>();
FakeAsync().run((FakeAsync time) {
expect(processMock.lastPubEnvironment, isNull);
@ -95,8 +95,8 @@ void main() {
testUsingContext('pub cache in root is used', () async {
String error;
final MockProcessManager processMock = context[ProcessManager];
final MockFileSystem fsMock = context[FileSystem];
final MockProcessManager processMock = context.get<ProcessManager>() as MockProcessManager;
final MockFileSystem fsMock = context.get<FileSystem>() as MockFileSystem;
FakeAsync().run((FakeAsync time) {
MockDirectory.findCache = true;
@ -122,7 +122,7 @@ void main() {
testUsingContext('pub cache in environment is used', () async {
String error;
final MockProcessManager processMock = context[ProcessManager];
final MockProcessManager processMock = context.get<ProcessManager>();
FakeAsync().run((FakeAsync time) {
MockDirectory.findCache = true;

View file

@ -30,10 +30,10 @@ import 'common.dart';
export 'package:flutter_tools/src/base/context.dart' show Generator;
/// 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];
MockDoctor get testDoctor => context[Doctor];
MockDeviceManager get testDeviceManager => context.get<DeviceManager>();
MockDoctor get testDoctor => context.get<Doctor>();
typedef ContextInitializer = void Function(AppContext testContext);
@ -126,8 +126,8 @@ void testUsingContext(
}
void _printBufferedErrors(AppContext testContext) {
if (testContext[Logger] is BufferLogger) {
final BufferLogger bufferLogger = testContext[Logger];
if (testContext.get<Logger>() is BufferLogger) {
final BufferLogger bufferLogger = testContext.get<Logger>();
if (bufferLogger.errorText.isNotEmpty)
print(bufferLogger.errorText);
bufferLogger.clear();

View file

@ -414,7 +414,7 @@ void main() {
}
void _expectVersionMessage(String message) {
final BufferLogger logger = context[Logger];
final BufferLogger logger = context.get<Logger>();
expect(logger.statusText.trim(), message.trim());
logger.clear();
}