[flutter_tools] Remove --no-sound-null-safety #4 (#124039)

Re-land of https://github.com/flutter/flutter/pull/123297 without any of
the commits at the end attempting to fix customer-testing.

Fixes https://github.com/flutter/flutter/issues/118810
This commit is contained in:
Christopher Fujino
2023-04-04 12:25:27 -10:00
committed by GitHub
parent 34d2c8d030
commit b2c65acd5a
9 changed files with 104 additions and 187 deletions

View File

@@ -43,6 +43,7 @@ import 'pre_run_validator.dart';
import 'project.dart';
import 'reporting/crash_reporting.dart';
import 'reporting/reporting.dart';
import 'runner/flutter_command.dart';
import 'runner/local_engine.dart';
import 'version.dart';
@@ -285,3 +286,7 @@ const String kDefaultFrameworkChannel = 'master';
// Used to build RegExp instances which can detect the VM service message.
final RegExp kVMServiceMessageRegExp = RegExp(r'The Dart VM service is listening on ((http|//)[a-zA-Z0-9:/=_\-\.\[\]]+)');
// The official tool no longer allows non-null safe builds. This can be
// overridden in other clients.
NonNullSafeBuilds get nonNullSafeBuilds => context.get<NonNullSafeBuilds>() ?? NonNullSafeBuilds.notAllowed;

View File

@@ -21,7 +21,6 @@ import '../bundle.dart' as bundle;
import '../cache.dart';
import '../convert.dart';
import '../dart/generate_synthetic_packages.dart';
import '../dart/language_version.dart';
import '../dart/package_map.dart';
import '../dart/pub.dart';
import '../device.dart';
@@ -822,20 +821,13 @@ abstract class FlutterCommand extends Command<void> {
void addNullSafetyModeOptions({ required bool hide }) {
argParser.addFlag(FlutterOptions.kNullSafety,
help:
'Whether to override the inferred null safety mode. This allows null-safe '
'libraries to depend on un-migrated (non-null safe) libraries. By default, '
'Flutter mobile & desktop applications will attempt to run at the null safety '
'level of their entrypoint library (usually lib/main.dart). Flutter web '
'applications will default to sound null-safety, unless specifically configured.',
help: 'This flag is deprecated as only null-safe code is supported.',
defaultsTo: true,
hide: hide,
hide: true,
);
argParser.addFlag(FlutterOptions.kNullAssertions,
help:
'Perform additional null assertions on the boundaries of migrated and '
'un-migrated code. This setting is not currently supported on desktop '
'devices.'
help: 'This flag is deprecated as only null-safe code is supported.',
hide: true,
);
}
@@ -1148,39 +1140,17 @@ abstract class FlutterCommand extends Command<void> {
NullSafetyMode nullSafetyMode = NullSafetyMode.sound;
if (argParser.options.containsKey(FlutterOptions.kNullSafety)) {
// Explicitly check for `true` and `false` so that `null` results in not
// passing a flag. Examine the entrypoint file to determine if it
// is opted in or out.
final bool wasNullSafetyFlagParsed = argResults?.wasParsed(FlutterOptions.kNullSafety) ?? false;
if (!wasNullSafetyFlagParsed && (argParser.options.containsKey('target') || forcedTargetFile != null)) {
final File entrypointFile = forcedTargetFile ?? globals.fs.file(targetFile);
final LanguageVersion languageVersion = determineLanguageVersion(
entrypointFile,
packageConfig.packageOf(entrypointFile.absolute.uri),
Cache.flutterRoot!,
);
// Extra frontend options are only provided if explicitly
// requested.
if ((languageVersion.major > nullSafeVersion.major) ||
(languageVersion.major == nullSafeVersion.major && languageVersion.minor >= nullSafeVersion.minor)) {
// Extra frontend options are only provided if explicitly
// requested.
if (wasNullSafetyFlagParsed) {
if (boolArg(FlutterOptions.kNullSafety)) {
nullSafetyMode = NullSafetyMode.sound;
extraFrontEndOptions.add('--sound-null-safety');
} else {
throwToolExit(
'This application does not support sound null-safety (its language version is $languageVersion).\n'
'To build this application, you must provide the CLI flag --no-sound-null-safety. Dart 3 will only '
'support sound null safety, see https://dart.dev/null-safety.',
);
nullSafetyMode = NullSafetyMode.unsound;
extraFrontEndOptions.add('--no-sound-null-safety');
}
} else if (!wasNullSafetyFlagParsed) {
// This mode is only used for commands which do not build a single target like
// 'flutter test'.
nullSafetyMode = NullSafetyMode.autodetect;
} else if (boolArg(FlutterOptions.kNullSafety)) {
nullSafetyMode = NullSafetyMode.sound;
extraFrontEndOptions.add('--sound-null-safety');
} else {
nullSafetyMode = NullSafetyMode.unsound;
extraFrontEndOptions.add('--no-sound-null-safety');
}
}
@@ -1487,6 +1457,16 @@ abstract class FlutterCommand extends Command<void> {
/// rather than calling [runCommand] directly.
@mustCallSuper
Future<FlutterCommandResult> verifyThenRunCommand(String? commandPath) async {
if (argParser.options.containsKey(FlutterOptions.kNullSafety) &&
argResults![FlutterOptions.kNullSafety] == false &&
globals.nonNullSafeBuilds == NonNullSafeBuilds.notAllowed) {
throwToolExit('''
Could not find an option named "no-${FlutterOptions.kNullSafety}".
Run 'flutter -h' (or 'flutter <command> -h') for available flutter commands and options.
''');
}
globals.preRunValidator.validate();
if (refreshWirelessDevices) {
@@ -1754,3 +1734,12 @@ DevelopmentArtifact? artifactFromTargetPlatform(TargetPlatform targetPlatform) {
/// Returns true if s is either null, empty or is solely made of whitespace characters (as defined by String.trim).
bool _isBlank(String s) => s.trim().isEmpty;
/// Whether the tool should allow non-null safe builds.
///
/// The Dart SDK no longer supports non-null safe builds, so this value in the
/// tool's context should always be [NonNullSafeBuilds.notAllowed].
enum NonNullSafeBuilds {
allowed,
notAllowed,
}

View File

@@ -67,6 +67,52 @@ void main() {
Logger: () => BufferLogger.test(),
});
testUsingContext('does not support --no-sound-null-safety by default', () async {
fileSystem.file('lib/main.dart').createSync(recursive: true);
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
final TestRunCommandThatOnlyValidates command = TestRunCommandThatOnlyValidates();
await expectLater(
() => createTestCommandRunner(command).run(<String>[
'run',
'--use-application-binary=app/bar/faz',
'--no-sound-null-safety',
]),
throwsA(isException.having(
(Exception exception) => exception.toString(),
'toString',
contains('Could not find an option named "no-sound-null-safety"'),
)),
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => FakeProcessManager.any(),
Logger: () => BufferLogger.test(),
});
testUsingContext('supports --no-sound-null-safety with an overridden NonNullSafeBuilds', () async {
fileSystem.file('lib/main.dart').createSync(recursive: true);
fileSystem.file('pubspec.yaml').createSync();
fileSystem.file('.packages').createSync();
final FakeDevice device = FakeDevice(isLocalEmulator: true, platformType: PlatformType.android);
testDeviceManager.devices = <Device>[device];
final TestRunCommandThatOnlyValidates command = TestRunCommandThatOnlyValidates();
await createTestCommandRunner(command).run(const <String>[
'run',
'--use-application-binary=app/bar/faz',
'--no-sound-null-safety',
]);
}, overrides: <Type, Generator>{
DeviceManager: () => testDeviceManager,
FileSystem: () => fileSystem,
Logger: () => BufferLogger.test(),
NonNullSafeBuilds: () => NonNullSafeBuilds.allowed,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('does not support "--use-application-binary" and "--fast-start"', () async {
fileSystem.file('lib/main.dart').createSync(recursive: true);
fileSystem.file('pubspec.yaml').createSync();

View File

@@ -176,7 +176,10 @@ void verifyOptions(String? command, Iterable<Option> options) {
expect(option.name, matches(_allowedArgumentNamePattern), reason: '$_header$target--${option.name}" is not a valid name for a command line argument. (Is it all lowercase? Does it use hyphens rather than underscores?)');
}
expect(option.name, isNot(matches(_bannedArgumentNamePattern)), reason: '$_header$target--${option.name}" is not a valid name for a command line argument. (We use "--foo-url", not "--foo-uri", for example.)');
expect(option.hide, isFalse, reason: '${_header}Help for $target--${option.name}" is always hidden. $_needHelp');
// The flag --sound-null-safety is deprecated
if (option.name != FlutterOptions.kNullSafety && option.name != FlutterOptions.kNullAssertions) {
expect(option.hide, isFalse, reason: '${_header}Help for $target--${option.name}" is always hidden. $_needHelp');
}
expect(option.help, isNotNull, reason: '${_header}Help for $target--${option.name}" has null help. $_needHelp');
expect(option.help, isNotEmpty, reason: '${_header}Help for $target--${option.name}" has empty help. $_needHelp');
expect(option.help, isNot(matches(_bannedLeadingPatterns)), reason: '${_header}A line in the help for $target--${option.name}" starts with a lowercase letter. For stylistic consistency, all help messages must start with a capital letter.');

View File

@@ -552,27 +552,6 @@ void main() {
ProcessManager: () => processManager,
});
testUsingContext('tool exits on non-sound-null-safe code when explicit flag not passed', () async {
final DummyFlutterCommand flutterCommand = DummyFlutterCommand(packagesPath: 'foo');
flutterCommand.argParser
..addFlag(FlutterOptions.kNullSafety, defaultsTo: true)
..addOption('target');
final File targetFile = fileSystem.file('targetFile.dart')
..writeAsStringSync('// @dart = 2.11');
expect(
() async => flutterCommand.getBuildInfo(
forcedBuildMode: BuildMode.debug,
forcedTargetFile: targetFile,
),
throwsToolExit(
message: 'This application does not support sound null-safety (its language version is 2.11)',
),
);
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,
});
testUsingContext('use packagesPath to generate BuildInfo', () async {
final DummyFlutterCommand flutterCommand = DummyFlutterCommand(packagesPath: 'foo');
final BuildInfo buildInfo = await flutterCommand.getBuildInfo(forcedBuildMode: BuildMode.debug);

View File

@@ -1,83 +0,0 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'package:flutter_tools/src/base/io.dart';
import '../src/common.dart';
import 'test_utils.dart';
void main() {
late Directory tempDir;
late Directory projectRoot;
late String flutterBin;
final List<String> targetPlatforms = <String>[
'apk',
'web',
if (platform.isWindows) 'windows',
if (platform.isMacOS) ...<String>['macos', 'ios'],
];
setUpAll(() {
tempDir = createResolvedTempDirectorySync('build_null_unsafe_test.');
flutterBin = fileSystem.path.join(
getFlutterRoot(),
'bin',
'flutter',
);
processManager.runSync(<String>[
flutterBin,
'config',
'--enable-macos-desktop',
'--enable-windows-desktop',
'--enable-web',
]);
processManager.runSync(<String>[
flutterBin,
...getLocalEngineArguments(),
'create',
'hello',
], workingDirectory: tempDir.path);
projectRoot = tempDir.childDirectory('hello');
writeFile(fileSystem.path.join(projectRoot.path, 'pubspec.yaml'), '''
name: hello
environment:
sdk: '>=2.12.0 <4.0.0'
''');
writeFile(fileSystem.path.join(projectRoot.path, 'lib', 'main.dart'), '''
import 'unsafe.dart';
void main() {
print(unsafeString);
}
''');
writeFile(fileSystem.path.join(projectRoot.path, 'lib', 'unsafe.dart'), '''
// @dart=2.9
String unsafeString = null;
''');
});
tearDownAll(() {
tryToDelete(tempDir);
});
for (final String targetPlatform in targetPlatforms) {
testWithoutContext('flutter build $targetPlatform --no-sound-null-safety', () {
final ProcessResult result = processManager.runSync(<String>[
flutterBin,
...getLocalEngineArguments(),
'build',
targetPlatform,
'--no-pub',
'--no-sound-null-safety',
if (targetPlatform == 'ios') '--no-codesign',
], workingDirectory: projectRoot.path);
if (result.exitCode != 0) {
fail('build --no-sound-null-safety failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}');
}
});
}
}