Unverified Commit 758009ba authored by Alexandre Ardhuin's avatar Alexandre Ardhuin Committed by GitHub

more ui-as-code (#35393)

* more ui-as-code

* address review comments
parent e2a55fe8
...@@ -531,10 +531,12 @@ linter: ...@@ -531,10 +531,12 @@ linter:
File _writeSection(Section section) { File _writeSection(Section section) {
final String sectionId = _createNameFromSource('sample', section.start.filename, section.start.line); final String sectionId = _createNameFromSource('sample', section.start.filename, section.start.line);
final File outputFile = File(path.join(_tempDirectory.path, '$sectionId.dart'))..createSync(recursive: true); final File outputFile = File(path.join(_tempDirectory.path, '$sectionId.dart'))..createSync(recursive: true);
final List<Line> mainContents = headers.toList(); final List<Line> mainContents = <Line>[
mainContents.add(const Line('')); ...headers,
mainContents.add(Line('// From: ${section.start.filename}:${section.start.line}')); const Line(''),
mainContents.addAll(section.code); Line('// From: ${section.start.filename}:${section.start.line}'),
...section.code,
];
outputFile.writeAsStringSync(mainContents.map<String>((Line line) => line.code).join('\n')); outputFile.writeAsStringSync(mainContents.map<String>((Line line) => line.code).join('\n'));
return outputFile; return outputFile;
} }
...@@ -820,10 +822,9 @@ class Line { ...@@ -820,10 +822,9 @@ class Line {
class Section { class Section {
const Section(this.code); const Section(this.code);
factory Section.combine(List<Section> sections) { factory Section.combine(List<Section> sections) {
final List<Line> code = <Line>[]; final List<Line> code = sections
for (Section section in sections) { .expand((Section section) => section.code)
code.addAll(section.code); .toList();
}
return Section(code); return Section(code);
} }
factory Section.fromStrings(Line firstLine, List<String> code) { factory Section.fromStrings(Line firstLine, List<String> code) {
......
...@@ -40,9 +40,10 @@ Future<void> main(List<String> args) async { ...@@ -40,9 +40,10 @@ Future<void> main(List<String> args) async {
{ {
// Analyze all the Dart code in the repo. // Analyze all the Dart code in the repo.
final List<String> options = <String>['--flutter-repo']; await _runFlutterAnalyze(flutterRoot, options: <String>[
options.addAll(args); '--flutter-repo',
await _runFlutterAnalyze(flutterRoot, options: options); ...args,
]);
} }
// Ensure that all package dependencies are in sync. // Ensure that all package dependencies are in sync.
...@@ -59,9 +60,12 @@ Future<void> main(List<String> args) async { ...@@ -59,9 +60,12 @@ Future<void> main(List<String> args) async {
// Try with the --watch analyzer, to make sure it returns success also. // Try with the --watch analyzer, to make sure it returns success also.
// The --benchmark argument exits after one run. // The --benchmark argument exits after one run.
{ {
final List<String> options = <String>['--flutter-repo', '--watch', '--benchmark']; await _runFlutterAnalyze(flutterRoot, options: <String>[
options.addAll(args); '--flutter-repo',
await _runFlutterAnalyze(flutterRoot, options: options); '--watch',
'--benchmark',
...args,
]);
} }
await _checkForTrailingSpaces(); await _checkForTrailingSpaces();
...@@ -79,9 +83,11 @@ Future<void> main(List<String> args) async { ...@@ -79,9 +83,11 @@ Future<void> main(List<String> args) async {
workingDirectory: flutterRoot, workingDirectory: flutterRoot,
); );
{ {
final List<String> options = <String>['--watch', '--benchmark']; await _runFlutterAnalyze(outDir.path, options: <String>[
options.addAll(args); '--watch',
await _runFlutterAnalyze(outDir.path, options: options); '--benchmark',
...args,
]);
} }
} finally { } finally {
outDir.deleteSync(recursive: true); outDir.deleteSync(recursive: true);
......
...@@ -601,14 +601,14 @@ class ArchivePublisher { ...@@ -601,14 +601,14 @@ class ArchivePublisher {
if (dest.endsWith('.json')) { if (dest.endsWith('.json')) {
mimeType = 'application/json'; mimeType = 'application/json';
} }
final List<String> args = <String>[]; return await _runGsUtil(<String>[
// Use our preferred MIME type for the files we care about // Use our preferred MIME type for the files we care about
// and let gsutil figure it out for anything else. // and let gsutil figure it out for anything else.
if (mimeType != null) { if (mimeType != null) ...<String>['-h', 'Content-Type:$mimeType'],
args.addAll(<String>['-h', 'Content-Type:$mimeType']); 'cp',
} src,
args.addAll(<String>['cp', src, dest]); dest,
return await _runGsUtil(args); ]);
} }
} }
......
...@@ -754,11 +754,13 @@ Future<void> _runFlutterWebTest(String workingDirectory, { ...@@ -754,11 +754,13 @@ Future<void> _runFlutterWebTest(String workingDirectory, {
Duration timeout = _kLongTimeout, Duration timeout = _kLongTimeout,
List<String> tests, List<String> tests,
}) async { }) async {
final List<String> args = <String>['test', '-v', '--platform=chrome']; final List<String> args = <String>[
if (flutterTestArgs != null && flutterTestArgs.isNotEmpty) 'test',
args.addAll(flutterTestArgs); '-v',
'--platform=chrome',
args.addAll(tests); ...?flutterTestArgs,
...tests,
];
// TODO(jonahwilliams): fix relative path issues to make this unecessary. // TODO(jonahwilliams): fix relative path issues to make this unecessary.
final Directory oldCurrent = Directory.current; final Directory oldCurrent = Directory.current;
...@@ -791,9 +793,11 @@ Future<void> _runFlutterTest(String workingDirectory, { ...@@ -791,9 +793,11 @@ Future<void> _runFlutterTest(String workingDirectory, {
Map<String, String> environment, Map<String, String> environment,
List<String> tests = const <String>[], List<String> tests = const <String>[],
}) async { }) async {
final List<String> args = <String>['test', ...options]; final List<String> args = <String>[
if (flutterTestArgs != null && flutterTestArgs.isNotEmpty) 'test',
args.addAll(flutterTestArgs); ...options,
...?flutterTestArgs,
];
final bool shouldProcessOutput = useFlutterTestFormatter && !expectFailure && !options.contains('--coverage'); final bool shouldProcessOutput = useFlutterTestFormatter && !expectFailure && !options.contains('--coverage');
if (shouldProcessOutput) { if (shouldProcessOutput) {
......
...@@ -106,16 +106,14 @@ void main() { ...@@ -106,16 +106,14 @@ void main() {
test('sets PUB_CACHE properly', () async { test('sets PUB_CACHE properly', () async {
final String createBase = path.join(tempDir.absolute.path, 'create_'); final String createBase = path.join(tempDir.absolute.path, 'create_');
final Map<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{ final String archiveName = path.join(tempDir.absolute.path,
'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}');
processManager.fakeResults = <String, List<ProcessResult>>{
'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null, 'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null,
'git reset --hard $testRef': null, 'git reset --hard $testRef': null,
'git remote set-url origin https://github.com/flutter/flutter.git': null, 'git remote set-url origin https://github.com/flutter/flutter.git': null,
'git describe --tags --exact-match $testRef': <ProcessResult>[ProcessResult(0, 0, 'v1.2.3', '')], 'git describe --tags --exact-match $testRef': <ProcessResult>[ProcessResult(0, 0, 'v1.2.3', '')],
}; if (platform.isWindows) '7za x ${path.join(tempDir.path, 'mingit.zip')}': null,
if (platform.isWindows) {
calls['7za x ${path.join(tempDir.path, 'mingit.zip')}'] = null;
}
calls.addAll(<String, List<ProcessResult>>{
'$flutter doctor': null, '$flutter doctor': null,
'$flutter update-packages': null, '$flutter update-packages': null,
'$flutter precache': null, '$flutter precache': null,
...@@ -124,17 +122,10 @@ void main() { ...@@ -124,17 +122,10 @@ void main() {
'$flutter create --template=package ${createBase}package': null, '$flutter create --template=package ${createBase}package': null,
'$flutter create --template=plugin ${createBase}plugin': null, '$flutter create --template=plugin ${createBase}plugin': null,
'git clean -f -X **/.packages': null, 'git clean -f -X **/.packages': null,
}); if (platform.isWindows) '7za a -tzip -mx=9 $archiveName flutter': null
final String archiveName = path.join(tempDir.absolute.path, else if (platform.isMacOS) 'zip -r -9 $archiveName flutter': null
'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}'); else if (platform.isLinux) 'tar cJf $archiveName flutter': null,
if (platform.isWindows) { };
calls['7za a -tzip -mx=9 $archiveName flutter'] = null;
} else if (platform.isMacOS) {
calls['zip -r -9 $archiveName flutter'] = null;
} else if (platform.isLinux) {
calls['tar cJf $archiveName flutter'] = null;
}
processManager.fakeResults = calls;
await creator.initializeRepo(); await creator.initializeRepo();
await creator.createArchive(); await creator.createArchive();
expect( expect(
...@@ -149,16 +140,14 @@ void main() { ...@@ -149,16 +140,14 @@ void main() {
test('calls the right commands for archive output', () async { test('calls the right commands for archive output', () async {
final String createBase = path.join(tempDir.absolute.path, 'create_'); final String createBase = path.join(tempDir.absolute.path, 'create_');
final String archiveName = path.join(tempDir.absolute.path,
'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}');
final Map<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{ final Map<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{
'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null, 'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null,
'git reset --hard $testRef': null, 'git reset --hard $testRef': null,
'git remote set-url origin https://github.com/flutter/flutter.git': null, 'git remote set-url origin https://github.com/flutter/flutter.git': null,
'git describe --tags --exact-match $testRef': <ProcessResult>[ProcessResult(0, 0, 'v1.2.3', '')], 'git describe --tags --exact-match $testRef': <ProcessResult>[ProcessResult(0, 0, 'v1.2.3', '')],
}; if (platform.isWindows) '7za x ${path.join(tempDir.path, 'mingit.zip')}': null,
if (platform.isWindows) {
calls['7za x ${path.join(tempDir.path, 'mingit.zip')}'] = null;
}
calls.addAll(<String, List<ProcessResult>>{
'$flutter doctor': null, '$flutter doctor': null,
'$flutter update-packages': null, '$flutter update-packages': null,
'$flutter precache': null, '$flutter precache': null,
...@@ -167,16 +156,10 @@ void main() { ...@@ -167,16 +156,10 @@ void main() {
'$flutter create --template=package ${createBase}package': null, '$flutter create --template=package ${createBase}package': null,
'$flutter create --template=plugin ${createBase}plugin': null, '$flutter create --template=plugin ${createBase}plugin': null,
'git clean -f -X **/.packages': null, 'git clean -f -X **/.packages': null,
}); if (platform.isWindows) '7za a -tzip -mx=9 $archiveName flutter': null
final String archiveName = path.join(tempDir.absolute.path, else if (platform.isMacOS) 'zip -r -9 $archiveName flutter': null
'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}'); else if (platform.isLinux) 'tar cJf $archiveName flutter': null,
if (platform.isWindows) { };
calls['7za a -tzip -mx=9 $archiveName flutter'] = null;
} else if (platform.isMacOS) {
calls['zip -r -9 $archiveName flutter'] = null;
} else if (platform.isLinux) {
calls['tar cJf $archiveName flutter'] = null;
}
processManager.fakeResults = calls; processManager.fakeResults = calls;
creator = ArchiveCreator( creator = ArchiveCreator(
tempDir, tempDir,
...@@ -206,16 +189,14 @@ void main() { ...@@ -206,16 +189,14 @@ void main() {
test('non-strict mode calls the right commands', () async { test('non-strict mode calls the right commands', () async {
final String createBase = path.join(tempDir.absolute.path, 'create_'); final String createBase = path.join(tempDir.absolute.path, 'create_');
final String archiveName = path.join(tempDir.absolute.path,
'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}');
final Map<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{ final Map<String, List<ProcessResult>> calls = <String, List<ProcessResult>>{
'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null, 'git clone -b dev https://chromium.googlesource.com/external/github.com/flutter/flutter': null,
'git reset --hard $testRef': null, 'git reset --hard $testRef': null,
'git remote set-url origin https://github.com/flutter/flutter.git': null, 'git remote set-url origin https://github.com/flutter/flutter.git': null,
'git describe --tags --abbrev=0 $testRef': <ProcessResult>[ProcessResult(0, 0, 'v1.2.3', '')], 'git describe --tags --abbrev=0 $testRef': <ProcessResult>[ProcessResult(0, 0, 'v1.2.3', '')],
}; if (platform.isWindows) '7za x ${path.join(tempDir.path, 'mingit.zip')}': null,
if (platform.isWindows) {
calls['7za x ${path.join(tempDir.path, 'mingit.zip')}'] = null;
}
calls.addAll(<String, List<ProcessResult>>{
'$flutter doctor': null, '$flutter doctor': null,
'$flutter update-packages': null, '$flutter update-packages': null,
'$flutter precache': null, '$flutter precache': null,
...@@ -224,16 +205,10 @@ void main() { ...@@ -224,16 +205,10 @@ void main() {
'$flutter create --template=package ${createBase}package': null, '$flutter create --template=package ${createBase}package': null,
'$flutter create --template=plugin ${createBase}plugin': null, '$flutter create --template=plugin ${createBase}plugin': null,
'git clean -f -X **/.packages': null, 'git clean -f -X **/.packages': null,
}); if (platform.isWindows) '7za a -tzip -mx=9 $archiveName flutter': null
final String archiveName = path.join(tempDir.absolute.path, else if (platform.isMacOS) 'zip -r -9 $archiveName flutter': null
'flutter_${platformName}_v1.2.3-dev${platform.isLinux ? '.tar.xz' : '.zip'}'); else if (platform.isLinux) 'tar cJf $archiveName flutter': null,
if (platform.isWindows) { };
calls['7za a -tzip -mx=9 $archiveName flutter'] = null;
} else if (platform.isMacOS) {
calls['zip -r -9 $archiveName flutter'] = null;
} else if (platform.isLinux) {
calls['tar cJf $archiveName flutter'] = null;
}
processManager.fakeResults = calls; processManager.fakeResults = calls;
creator = ArchiveCreator( creator = ArchiveCreator(
tempDir, tempDir,
......
...@@ -377,13 +377,12 @@ class ArchiveUnpublisher { ...@@ -377,13 +377,12 @@ class ArchiveUnpublisher {
if (dest.endsWith('.json')) { if (dest.endsWith('.json')) {
mimeType = 'application/json'; mimeType = 'application/json';
} }
final List<String> args = <String>[]; final List<String> args = <String>[
// Use our preferred MIME type for the files we care about // Use our preferred MIME type for the files we care about
// and let gsutil figure it out for anything else. // and let gsutil figure it out for anything else.
if (mimeType != null) { if (mimeType != null) ...<String>['-h', 'Content-Type:$mimeType'],
args.addAll(<String>['-h', 'Content-Type:$mimeType']); ...<String>['cp', src, dest],
} ];
args.addAll(<String>['cp', src, dest]);
return await _runGsUtil(args, confirm: confirmed); return await _runGsUtil(args, confirm: confirmed);
} }
} }
......
...@@ -252,10 +252,10 @@ Future<ProcessResult> _resultOfGradleTask({String workingDirectory, String task, ...@@ -252,10 +252,10 @@ Future<ProcessResult> _resultOfGradleTask({String workingDirectory, String task,
print('\nUsing JAVA_HOME=$javaHome'); print('\nUsing JAVA_HOME=$javaHome');
final List<String> args = <String>['app:$task']; final List<String> args = <String>[
if (options != null) { 'app:$task',
args.addAll(options); ...?options,
} ];
final String gradle = Platform.isWindows ? 'gradlew.bat' : './gradlew'; final String gradle = Platform.isWindows ? 'gradlew.bat' : './gradlew';
print('Running Gradle: ${path.join(workingDirectory, gradle)} ${args.join(' ')}'); print('Running Gradle: ${path.join(workingDirectory, gradle)} ${args.join(' ')}');
print(File(path.join(workingDirectory, gradle)).readAsStringSync()); print(File(path.join(workingDirectory, gradle)).readAsStringSync());
......
...@@ -28,11 +28,12 @@ Future<TaskResult> analyzerBenchmarkTask() async { ...@@ -28,11 +28,12 @@ Future<TaskResult> analyzerBenchmarkTask() async {
await dart(<String>['dev/tools/mega_gallery.dart', '--out=${_megaGalleryDirectory.path}']); await dart(<String>['dev/tools/mega_gallery.dart', '--out=${_megaGalleryDirectory.path}']);
}); });
final Map<String, dynamic> data = <String, dynamic>{}; final Map<String, dynamic> data = <String, dynamic>{
data.addAll((await _run(_FlutterRepoBenchmark())).asMap('flutter_repo', 'batch')); ...(await _run(_FlutterRepoBenchmark())).asMap('flutter_repo', 'batch'),
data.addAll((await _run(_FlutterRepoBenchmark(watch: true))).asMap('flutter_repo', 'watch')); ...(await _run(_FlutterRepoBenchmark(watch: true))).asMap('flutter_repo', 'watch'),
data.addAll((await _run(_MegaGalleryBenchmark())).asMap('mega_gallery', 'batch')); ...(await _run(_MegaGalleryBenchmark())).asMap('mega_gallery', 'batch'),
data.addAll((await _run(_MegaGalleryBenchmark(watch: true))).asMap('mega_gallery', 'watch')); ...(await _run(_MegaGalleryBenchmark(watch: true))).asMap('mega_gallery', 'watch'),
};
return TaskResult.success(data, benchmarkScoreKeys: data.keys.toList()); return TaskResult.success(data, benchmarkScoreKeys: data.keys.toList());
} }
......
...@@ -64,8 +64,8 @@ class GalleryTransitionTest { ...@@ -64,8 +64,8 @@ class GalleryTransitionTest {
final Map<String, dynamic> data = <String, dynamic>{ final Map<String, dynamic> data = <String, dynamic>{
'transitions': transitions, 'transitions': transitions,
'missed_transition_count': _countMissedTransitions(transitions), 'missed_transition_count': _countMissedTransitions(transitions),
...summary,
}; };
data.addAll(summary);
return TaskResult.success(data, benchmarkScoreKeys: <String>[ return TaskResult.success(data, benchmarkScoreKeys: <String>[
'missed_transition_count', 'missed_transition_count',
......
...@@ -124,8 +124,8 @@ class DriverTest { ...@@ -124,8 +124,8 @@ class DriverTest {
testTarget, testTarget,
'-d', '-d',
deviceId, deviceId,
...extraOptions,
]; ];
options.addAll(extraOptions);
await flutter('drive', options: options, environment: Map<String, String>.from(environment)); await flutter('drive', options: options, environment: Map<String, String>.from(environment));
return TaskResult.success(null); return TaskResult.success(null);
......
...@@ -48,13 +48,14 @@ TaskFunction createMicrobenchmarkTask() { ...@@ -48,13 +48,14 @@ TaskFunction createMicrobenchmarkTask() {
return _run(); return _run();
} }
final Map<String, double> allResults = <String, double>{}; final Map<String, double> allResults = <String, double>{
allResults.addAll(await _runMicrobench('lib/stocks/layout_bench.dart')); ...await _runMicrobench('lib/stocks/layout_bench.dart'),
allResults.addAll(await _runMicrobench('lib/stocks/build_bench.dart')); ...await _runMicrobench('lib/stocks/build_bench.dart'),
allResults.addAll(await _runMicrobench('lib/geometry/rrect_contains_bench.dart')); ...await _runMicrobench('lib/geometry/rrect_contains_bench.dart'),
allResults.addAll(await _runMicrobench('lib/gestures/velocity_tracker_bench.dart')); ...await _runMicrobench('lib/gestures/velocity_tracker_bench.dart'),
allResults.addAll(await _runMicrobench('lib/gestures/gesture_detector_bench.dart')); ...await _runMicrobench('lib/gestures/gesture_detector_bench.dart'),
allResults.addAll(await _runMicrobench('lib/stocks/animation_bench.dart')); ...await _runMicrobench('lib/stocks/animation_bench.dart'),
};
return TaskResult.success(allResults, benchmarkScoreKeys: allResults.keys.toList()); return TaskResult.success(allResults, benchmarkScoreKeys: allResults.keys.toList());
}; };
......
...@@ -289,10 +289,11 @@ class CompileTest { ...@@ -289,10 +289,11 @@ class CompileTest {
await device.unlock(); await device.unlock();
await flutter('packages', options: <String>['get']); await flutter('packages', options: <String>['get']);
final Map<String, dynamic> metrics = <String, dynamic>{} final Map<String, dynamic> metrics = <String, dynamic>{
..addAll(await _compileAot()) ...await _compileAot(),
..addAll(await _compileApp(reportPackageContentSizes: reportPackageContentSizes)) ...await _compileApp(reportPackageContentSizes: reportPackageContentSizes),
..addAll(await _compileDebug()); ...await _compileDebug(),
};
return TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList()); return TaskResult.success(metrics, benchmarkScoreKeys: metrics.keys.toList());
}); });
...@@ -533,10 +534,11 @@ class MemoryTest { ...@@ -533,10 +534,11 @@ class MemoryTest {
final ListStatistics endMemoryStatistics = ListStatistics(_endMemory); final ListStatistics endMemoryStatistics = ListStatistics(_endMemory);
final ListStatistics diffMemoryStatistics = ListStatistics(_diffMemory); final ListStatistics diffMemoryStatistics = ListStatistics(_diffMemory);
final Map<String, dynamic> memoryUsage = <String, dynamic>{}; final Map<String, dynamic> memoryUsage = <String, dynamic>{
memoryUsage.addAll(startMemoryStatistics.asMap('start')); ...startMemoryStatistics.asMap('start'),
memoryUsage.addAll(endMemoryStatistics.asMap('end')); ...endMemoryStatistics.asMap('end'),
memoryUsage.addAll(diffMemoryStatistics.asMap('diff')); ...diffMemoryStatistics.asMap('diff'),
};
_device = null; _device = null;
_startMemory.clear(); _startMemory.clear();
......
...@@ -15,14 +15,12 @@ void main() { ...@@ -15,14 +15,12 @@ void main() {
group('run.dart script', () { group('run.dart script', () {
Future<ProcessResult> runScript(List<String> testNames) async { Future<ProcessResult> runScript(List<String> testNames) async {
final List<String> options = <String>['bin/run.dart'];
for (String testName in testNames) {
options..addAll(<String>['-t', testName]);
}
final String dart = path.absolute(path.join('..', '..', 'bin', 'cache', 'dart-sdk', 'bin', 'dart')); final String dart = path.absolute(path.join('..', '..', 'bin', 'cache', 'dart-sdk', 'bin', 'dart'));
final ProcessResult scriptProcess = processManager.runSync( final ProcessResult scriptProcess = processManager.runSync(<String>[
<String>[dart, ...options] dart,
); 'bin/run.dart',
for (String testName in testNames) ...<String>['-t', testName],
]);
return scriptProcess; return scriptProcess;
} }
......
...@@ -1401,8 +1401,7 @@ String zalgo(math.Random random, int targetLength, { bool includeSpacingCombinin ...@@ -1401,8 +1401,7 @@ String zalgo(math.Random random, int targetLength, { bool includeSpacingCombinin
} }
} }
base ??= String.fromCharCode(randomCharacter(random)); base ??= String.fromCharCode(randomCharacter(random));
final List<int> characters = <int>[]; final List<int> characters = these.toList();
characters.addAll(these);
return base + String.fromCharCodes(characters); return base + String.fromCharCodes(characters);
} }
......
...@@ -127,15 +127,16 @@ class SnippetGenerator { ...@@ -127,15 +127,16 @@ class SnippetGenerator {
'description': description, 'description': description,
'code': htmlEscape.convert(result.join('\n')), 'code': htmlEscape.convert(result.join('\n')),
'language': language ?? 'dart', 'language': language ?? 'dart',
}..addAll(type == SnippetType.application 'serial': '',
? <String, String>{ 'id': '',
'serial': metadata['serial'].toString() ?? '0', 'app': '',
'id': };
injections.firstWhere((_ComponentTuple tuple) => tuple.name == 'id').mergedContent, if (type == SnippetType.application) {
'app': substitutions
htmlEscape.convert(injections.firstWhere((_ComponentTuple tuple) => tuple.name == 'app').mergedContent), ..['serial'] = metadata['serial'].toString() ?? '0'
} ..['id'] = injections.firstWhere((_ComponentTuple tuple) => tuple.name == 'id').mergedContent
: <String, String>{'serial': '', 'id': '', 'app': ''}); ..['app'] = htmlEscape.convert(injections.firstWhere((_ComponentTuple tuple) => tuple.name == 'app').mergedContent);
}
return skeleton.replaceAllMapped(RegExp('{{(${substitutions.keys.join('|')})}}'), (Match match) { return skeleton.replaceAllMapped(RegExp('{{(${substitutions.keys.join('|')})}}'), (Match match) {
return substitutions[match[1]]; return substitutions[match[1]];
}); });
......
...@@ -99,26 +99,24 @@ class PaletteTabView extends StatelessWidget { ...@@ -99,26 +99,24 @@ class PaletteTabView extends StatelessWidget {
final TextTheme textTheme = Theme.of(context).textTheme; final TextTheme textTheme = Theme.of(context).textTheme;
final TextStyle whiteTextStyle = textTheme.body1.copyWith(color: Colors.white); final TextStyle whiteTextStyle = textTheme.body1.copyWith(color: Colors.white);
final TextStyle blackTextStyle = textTheme.body1.copyWith(color: Colors.black); final TextStyle blackTextStyle = textTheme.body1.copyWith(color: Colors.black);
final List<Widget> colorItems = primaryKeys.map<Widget>((int index) {
return DefaultTextStyle(
style: index > colors.threshold ? whiteTextStyle : blackTextStyle,
child: ColorItem(index: index, color: colors.primary[index]),
);
}).toList();
if (colors.accent != null) {
colorItems.addAll(accentKeys.map<Widget>((int index) {
return DefaultTextStyle(
style: index > colors.threshold ? whiteTextStyle : blackTextStyle,
child: ColorItem(index: index, color: colors.accent[index], prefix: 'A'),
);
}).toList());
}
return Scrollbar( return Scrollbar(
child: ListView( child: ListView(
itemExtent: kColorItemHeight, itemExtent: kColorItemHeight,
children: colorItems, children: <Widget>[
...primaryKeys.map<Widget>((int index) {
return DefaultTextStyle(
style: index > colors.threshold ? whiteTextStyle : blackTextStyle,
child: ColorItem(index: index, color: colors.primary[index]),
);
}),
if (colors.accent != null)
...accentKeys.map<Widget>((int index) {
return DefaultTextStyle(
style: index > colors.threshold ? whiteTextStyle : blackTextStyle,
child: ColorItem(index: index, color: colors.accent[index], prefix: 'A'),
);
}),
],
) )
); );
} }
......
...@@ -349,52 +349,42 @@ class _DemoBottomAppBar extends StatelessWidget { ...@@ -349,52 +349,42 @@ class _DemoBottomAppBar extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final List<Widget> rowContents = <Widget> [
IconButton(
icon: const Icon(Icons.menu, semanticLabel: 'Show bottom sheet'),
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) => const _DemoDrawer(),
);
},
),
];
if (kCenterLocations.contains(fabLocation)) {
rowContents.add(
const Expanded(child: SizedBox()),
);
}
rowContents.addAll(<Widget> [
IconButton(
icon: const Icon(Icons.search, semanticLabel: 'show search action',),
onPressed: () {
Scaffold.of(context).showSnackBar(
const SnackBar(content: Text('This is a dummy search action.')),
);
},
),
IconButton(
icon: Icon(
Theme.of(context).platform == TargetPlatform.iOS
? Icons.more_horiz
: Icons.more_vert,
semanticLabel: 'Show menu actions',
),
onPressed: () {
Scaffold.of(context).showSnackBar(
const SnackBar(content: Text('This is a dummy menu action.')),
);
},
),
]);
return BottomAppBar( return BottomAppBar(
color: color, color: color,
child: Row(children: rowContents),
shape: shape, shape: shape,
child: Row(children: <Widget>[
IconButton(
icon: const Icon(Icons.menu, semanticLabel: 'Show bottom sheet'),
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) => const _DemoDrawer(),
);
},
),
if (kCenterLocations.contains(fabLocation)) const Expanded(child: SizedBox()),
IconButton(
icon: const Icon(Icons.search, semanticLabel: 'show search action',),
onPressed: () {
Scaffold.of(context).showSnackBar(
const SnackBar(content: Text('This is a dummy search action.')),
);
},
),
IconButton(
icon: Icon(
Theme.of(context).platform == TargetPlatform.iOS
? Icons.more_horiz
: Icons.more_vert,
semanticLabel: 'Show menu actions',
),
onPressed: () {
Scaffold.of(context).showSnackBar(
const SnackBar(content: Text('This is a dummy menu action.')),
);
},
),
]),
); );
} }
} }
......
...@@ -97,7 +97,8 @@ class TabbedComponentDemoScaffold extends StatelessWidget { ...@@ -97,7 +97,8 @@ class TabbedComponentDemoScaffold extends StatelessWidget {
child: Scaffold( child: Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text(title), title: Text(title),
actions: (actions ?? <Widget>[])..add( actions: <Widget>[
...?actions,
Builder( Builder(
builder: (BuildContext context) { builder: (BuildContext context) {
return IconButton( return IconButton(
...@@ -106,17 +107,17 @@ class TabbedComponentDemoScaffold extends StatelessWidget { ...@@ -106,17 +107,17 @@ class TabbedComponentDemoScaffold extends StatelessWidget {
); );
}, },
), ),
)..addAll(showExampleCodeAction ? <Widget>[ if (showExampleCodeAction)
Builder( Builder(
builder: (BuildContext context) { builder: (BuildContext context) {
return IconButton( return IconButton(
icon: const Icon(Icons.code), icon: const Icon(Icons.code),
tooltip: 'Show example code', tooltip: 'Show example code',
onPressed: () => _showExampleCode(context), onPressed: () => _showExampleCode(context),
); );
}, },
), ),
] : <Widget>[]), ],
bottom: TabBar( bottom: TabBar(
isScrollable: isScrollable, isScrollable: isScrollable,
tabs: demos.map<Widget>((ComponentDemoTabData data) => Tab(text: data.tabName)).toList(), tabs: demos.map<Widget>((ComponentDemoTabData data) => Tab(text: data.tabName)).toList(),
......
...@@ -477,12 +477,10 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti ...@@ -477,12 +477,10 @@ class FlutterError extends Error with DiagnosticableTreeMixin implements Asserti
/// using [ErrorHint]s or other [DiagnosticsNode]s. /// using [ErrorHint]s or other [DiagnosticsNode]s.
factory FlutterError(String message) { factory FlutterError(String message) {
final List<String> lines = message.split('\n'); final List<String> lines = message.split('\n');
final List<DiagnosticsNode> parts = <DiagnosticsNode>[]; return FlutterError.fromParts(<DiagnosticsNode>[
parts.add(ErrorSummary(lines.first)); ErrorSummary(lines.first),
if (lines.length > 1) { ...lines.skip(1).map<DiagnosticsNode>((String line) => ErrorDescription(line)),
parts.addAll(lines.skip(1).map<DiagnosticsNode>((String line) => ErrorDescription(line))); ]);
}
return FlutterError.fromParts(parts);
} }
/// Create an error message from a list of [DiagnosticsNode]s. /// Create an error message from a list of [DiagnosticsNode]s.
......
...@@ -1541,61 +1541,46 @@ abstract class DiagnosticsNode { ...@@ -1541,61 +1541,46 @@ abstract class DiagnosticsNode {
if (kReleaseMode) { if (kReleaseMode) {
return <String, Object>{}; return <String, Object>{};
} }
final Map<String, Object> data = <String, Object>{ final bool hasChildren = getChildren().isNotEmpty;
return <String, Object>{
'description': toDescription(), 'description': toDescription(),
'type': runtimeType.toString(), 'type': runtimeType.toString(),
if (name != null)
'name': name,
if (!showSeparator)
'showSeparator': showSeparator,
if (level != DiagnosticLevel.info)
'level': describeEnum(level),
if (showName == false)
'showName': showName,
if (emptyBodyDescription != null)
'emptyBodyDescription': emptyBodyDescription,
if (style != DiagnosticsTreeStyle.sparse)
'style': describeEnum(style),
if (allowTruncate)
'allowTruncate': allowTruncate,
if (hasChildren)
'hasChildren': hasChildren,
if (linePrefix?.isNotEmpty == true)
'linePrefix': linePrefix,
if (!allowWrap)
'allowWrap': allowWrap,
if (allowNameWrap)
'allowNameWrap': allowNameWrap,
...delegate.additionalNodeProperties(this),
if (delegate.includeProperties)
'properties': toJsonList(
delegate.filterProperties(getProperties(), this),
this,
delegate,
),
if (delegate.subtreeDepth > 0)
'children': toJsonList(
delegate.filterChildren(getChildren(), this),
this,
delegate,
),
}; };
if (name != null)
data['name'] = name;
if (!showSeparator)
data['showSeparator'] = showSeparator;
if (level != DiagnosticLevel.info)
data['level'] = describeEnum(level);
if (showName == false)
data['showName'] = showName;
if (emptyBodyDescription != null)
data['emptyBodyDescription'] = emptyBodyDescription;
if (style != DiagnosticsTreeStyle.sparse)
data['style'] = describeEnum(style);
if (allowTruncate)
data['allowTruncate'] = allowTruncate;
final bool hasChildren = getChildren().isNotEmpty;
if (hasChildren)
data['hasChildren'] = hasChildren;
if (linePrefix?.isNotEmpty == true)
data['linePrefix'] = linePrefix;
if (!allowWrap)
data['allowWrap'] = allowWrap;
if (allowNameWrap)
data['allowNameWrap'] = allowNameWrap;
data.addAll(delegate.additionalNodeProperties(this));
if (delegate.includeProperties) {
final List<DiagnosticsNode> properties = getProperties();
data['properties'] = toJsonList(
delegate.filterProperties(properties, this),
this,
delegate,
);
}
if (delegate.subtreeDepth > 0) {
final List<DiagnosticsNode> children = getChildren();
data['children'] = toJsonList(
delegate.filterChildren(children, this),
this,
delegate,
);
}
return data;
} }
/// Serializes a [List] of [DiagnosticsNode]s to a JSON list according to /// Serializes a [List] of [DiagnosticsNode]s to a JSON list according to
......
...@@ -268,34 +268,33 @@ class AboutDialog extends StatelessWidget { ...@@ -268,34 +268,33 @@ class AboutDialog extends StatelessWidget {
final String name = applicationName ?? _defaultApplicationName(context); final String name = applicationName ?? _defaultApplicationName(context);
final String version = applicationVersion ?? _defaultApplicationVersion(context); final String version = applicationVersion ?? _defaultApplicationVersion(context);
final Widget icon = applicationIcon ?? _defaultApplicationIcon(context); final Widget icon = applicationIcon ?? _defaultApplicationIcon(context);
List<Widget> body = <Widget>[]; return AlertDialog(
if (icon != null) content: SingleChildScrollView(
body.add(IconTheme(data: const IconThemeData(size: 48.0), child: icon));
body.add(Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: ListBody( child: ListBody(
children: <Widget>[ children: <Widget>[
Text(name, style: Theme.of(context).textTheme.headline), Row(
Text(version, style: Theme.of(context).textTheme.body1), crossAxisAlignment: CrossAxisAlignment.start,
Container(height: 18.0), children: <Widget>[
Text(applicationLegalese ?? '', style: Theme.of(context).textTheme.caption), if (icon != null) IconTheme(data: const IconThemeData(size: 48.0), child: icon),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0),
child: ListBody(
children: <Widget>[
Text(name, style: Theme.of(context).textTheme.headline),
Text(version, style: Theme.of(context).textTheme.body1),
Container(height: 18.0),
Text(applicationLegalese ?? '', style: Theme.of(context).textTheme.caption),
],
),
),
),
],
),
...?children,
], ],
), ),
), ),
));
body = <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: body,
),
];
if (children != null)
body.addAll(children);
return AlertDialog(
content: SingleChildScrollView(
child: ListBody(children: body),
),
actions: <Widget>[ actions: <Widget>[
FlatButton( FlatButton(
child: Text(MaterialLocalizations.of(context).viewLicensesButtonLabel), child: Text(MaterialLocalizations.of(context).viewLicensesButtonLabel),
...@@ -457,24 +456,6 @@ class _LicensePageState extends State<LicensePage> { ...@@ -457,24 +456,6 @@ class _LicensePageState extends State<LicensePage> {
final String name = widget.applicationName ?? _defaultApplicationName(context); final String name = widget.applicationName ?? _defaultApplicationName(context);
final String version = widget.applicationVersion ?? _defaultApplicationVersion(context); final String version = widget.applicationVersion ?? _defaultApplicationVersion(context);
final MaterialLocalizations localizations = MaterialLocalizations.of(context); final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final List<Widget> contents = <Widget>[
Text(name, style: Theme.of(context).textTheme.headline, textAlign: TextAlign.center),
Text(version, style: Theme.of(context).textTheme.body1, textAlign: TextAlign.center),
Container(height: 18.0),
Text(widget.applicationLegalese ?? '', style: Theme.of(context).textTheme.caption, textAlign: TextAlign.center),
Container(height: 18.0),
Text('Powered by Flutter', style: Theme.of(context).textTheme.body1, textAlign: TextAlign.center),
Container(height: 24.0),
];
contents.addAll(_licenses);
if (!_loaded) {
contents.add(const Padding(
padding: EdgeInsets.symmetric(vertical: 24.0),
child: Center(
child: CircularProgressIndicator(),
),
));
}
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text(localizations.licensesPageTitle), title: Text(localizations.licensesPageTitle),
...@@ -491,7 +472,23 @@ class _LicensePageState extends State<LicensePage> { ...@@ -491,7 +472,23 @@ class _LicensePageState extends State<LicensePage> {
child: Scrollbar( child: Scrollbar(
child: ListView( child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 12.0), padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 12.0),
children: contents, children: <Widget>[
Text(name, style: Theme.of(context).textTheme.headline, textAlign: TextAlign.center),
Text(version, style: Theme.of(context).textTheme.body1, textAlign: TextAlign.center),
Container(height: 18.0),
Text(widget.applicationLegalese ?? '', style: Theme.of(context).textTheme.caption, textAlign: TextAlign.center),
Container(height: 18.0),
Text('Powered by Flutter', style: Theme.of(context).textTheme.body1, textAlign: TextAlign.center),
Container(height: 24.0),
..._licenses,
if (!_loaded)
const Padding(
padding: EdgeInsets.symmetric(vertical: 24.0),
child: Center(
child: CircularProgressIndicator(),
),
)
],
), ),
), ),
), ),
......
...@@ -392,8 +392,9 @@ class DayPicker extends StatelessWidget { ...@@ -392,8 +392,9 @@ class DayPicker extends StatelessWidget {
final int month = displayedMonth.month; final int month = displayedMonth.month;
final int daysInMonth = getDaysInMonth(year, month); final int daysInMonth = getDaysInMonth(year, month);
final int firstDayOffset = _computeFirstDayOffset(year, month, localizations); final int firstDayOffset = _computeFirstDayOffset(year, month, localizations);
final List<Widget> labels = <Widget>[]; final List<Widget> labels = <Widget>[
labels.addAll(_getDayHeaders(themeData.textTheme.caption, localizations)); ..._getDayHeaders(themeData.textTheme.caption, localizations),
];
for (int i = 0; true; i += 1) { for (int i = 0; true; i += 1) {
// 1-based day of month, e.g. 1-31 for January, and 1-29 for February on // 1-based day of month, e.g. 1-31 for January, and 1-29 for February on
// a leap year. // a leap year.
......
...@@ -2110,14 +2110,12 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin { ...@@ -2110,14 +2110,12 @@ class ScaffoldState extends State<Scaffold> with TickerProviderStateMixin {
} }
if (_currentBottomSheet != null || _dismissedBottomSheets.isNotEmpty) { if (_currentBottomSheet != null || _dismissedBottomSheets.isNotEmpty) {
final List<Widget> bottomSheets = <Widget>[];
if (_dismissedBottomSheets.isNotEmpty)
bottomSheets.addAll(_dismissedBottomSheets);
if (_currentBottomSheet != null)
bottomSheets.add(_currentBottomSheet._widget);
final Widget stack = Stack( final Widget stack = Stack(
children: bottomSheets,
alignment: Alignment.bottomCenter, alignment: Alignment.bottomCenter,
children: <Widget>[
..._dismissedBottomSheets,
if (_currentBottomSheet != null) _currentBottomSheet._widget,
],
); );
_addIfNonNull( _addIfNonNull(
children, children,
......
...@@ -528,22 +528,18 @@ class _CompoundBorder extends ShapeBorder { ...@@ -528,22 +528,18 @@ class _CompoundBorder extends ShapeBorder {
final ShapeBorder merged = ours.add(other, reversed: reversed) final ShapeBorder merged = ours.add(other, reversed: reversed)
?? other.add(ours, reversed: !reversed); ?? other.add(ours, reversed: !reversed);
if (merged != null) { if (merged != null) {
final List<ShapeBorder> result = <ShapeBorder>[]; final List<ShapeBorder> result = <ShapeBorder>[...borders];
result.addAll(borders);
result[reversed ? result.length - 1 : 0] = merged; result[reversed ? result.length - 1 : 0] = merged;
return _CompoundBorder(result); return _CompoundBorder(result);
} }
} }
// We can't, so fall back to just adding the new border to the list. // We can't, so fall back to just adding the new border to the list.
final List<ShapeBorder> mergedBorders = <ShapeBorder>[]; final List<ShapeBorder> mergedBorders = <ShapeBorder>[
if (reversed) if (reversed) ...borders,
mergedBorders.addAll(borders); if (other is _CompoundBorder) ...other.borders
if (other is _CompoundBorder) else other,
mergedBorders.addAll(other.borders); if (!reversed) ...borders,
else ];
mergedBorders.add(other);
if (!reversed)
mergedBorders.addAll(borders);
return _CompoundBorder(mergedBorders); return _CompoundBorder(mergedBorders);
} }
......
...@@ -498,13 +498,11 @@ class BoxConstraints extends Constraints { ...@@ -498,13 +498,11 @@ class BoxConstraints extends Constraints {
}) { }) {
assert(() { assert(() {
void throwError(DiagnosticsNode message) { void throwError(DiagnosticsNode message) {
final List<DiagnosticsNode> information = <DiagnosticsNode>[message]; throw FlutterError.fromParts(<DiagnosticsNode>[
if (informationCollector != null) { message,
information.addAll(informationCollector()); if (informationCollector != null) ...informationCollector(),
} DiagnosticsProperty<BoxConstraints>('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty),
]);
information.add(DiagnosticsProperty<BoxConstraints>('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty));
throw FlutterError.fromParts(information);
} }
if (minWidth.isNaN || maxWidth.isNaN || minHeight.isNaN || maxHeight.isNaN) { if (minWidth.isNaN || maxWidth.isNaN || minHeight.isNaN || maxHeight.isNaN) {
final List<String> affectedFieldsList = <String>[]; final List<String> affectedFieldsList = <String>[];
...@@ -1952,12 +1950,12 @@ abstract class RenderBox extends RenderObject { ...@@ -1952,12 +1950,12 @@ abstract class RenderBox extends RenderObject {
information.add(node.describeForError('The nearest ancestor providing an unbounded height constraint is')); information.add(node.describeForError('The nearest ancestor providing an unbounded height constraint is'));
} }
final List<DiagnosticsNode> errorParts = <DiagnosticsNode>[]; throw FlutterError.fromParts(<DiagnosticsNode>[
errorParts.addAll(information); ...information,
errorParts.add(DiagnosticsProperty<BoxConstraints>('The constraints that applied to the $runtimeType were', constraints, style: DiagnosticsTreeStyle.errorProperty)); DiagnosticsProperty<BoxConstraints>('The constraints that applied to the $runtimeType were', constraints, style: DiagnosticsTreeStyle.errorProperty),
errorParts.add(DiagnosticsProperty<Size>('The exact size it was given was', _size, style: DiagnosticsTreeStyle.errorProperty)); DiagnosticsProperty<Size>('The exact size it was given was', _size, style: DiagnosticsTreeStyle.errorProperty),
errorParts.add(ErrorHint('See https://flutter.dev/docs/development/ui/layout/box-constraints for more information.')); ErrorHint('See https://flutter.dev/docs/development/ui/layout/box-constraints for more information.'),
throw FlutterError.fromParts(errorParts); ]);
} }
// verify that the size is within the constraints // verify that the size is within the constraints
if (!constraints.isSatisfiedBy(_size)) { if (!constraints.isSatisfiedBy(_size)) {
......
...@@ -628,12 +628,11 @@ class RenderCustomPaint extends RenderProxyBox { ...@@ -628,12 +628,11 @@ class RenderCustomPaint extends RenderProxyBox {
final bool hasBackgroundSemantics = _backgroundSemanticsNodes != null && _backgroundSemanticsNodes.isNotEmpty; final bool hasBackgroundSemantics = _backgroundSemanticsNodes != null && _backgroundSemanticsNodes.isNotEmpty;
final bool hasForegroundSemantics = _foregroundSemanticsNodes != null && _foregroundSemanticsNodes.isNotEmpty; final bool hasForegroundSemantics = _foregroundSemanticsNodes != null && _foregroundSemanticsNodes.isNotEmpty;
final List<SemanticsNode> finalChildren = <SemanticsNode>[]; final List<SemanticsNode> finalChildren = <SemanticsNode>[
if (hasBackgroundSemantics) if (hasBackgroundSemantics) ..._backgroundSemanticsNodes,
finalChildren.addAll(_backgroundSemanticsNodes); ...children,
finalChildren.addAll(children); if (hasForegroundSemantics) ..._foregroundSemanticsNodes,
if (hasForegroundSemantics) ];
finalChildren.addAll(_foregroundSemanticsNodes);
super.assembleSemanticsNode(node, config, finalChildren); super.assembleSemanticsNode(node, config, finalChildren);
} }
......
...@@ -3326,15 +3326,16 @@ class _RootSemanticsFragment extends _InterestingSemanticsFragment { ...@@ -3326,15 +3326,16 @@ class _RootSemanticsFragment extends _InterestingSemanticsFragment {
node.rect = owner.semanticBounds; node.rect = owner.semanticBounds;
final List<SemanticsNode> children = <SemanticsNode>[]; final List<SemanticsNode> children = _children
for (_InterestingSemanticsFragment fragment in _children) { .expand((_InterestingSemanticsFragment fragment) {
assert(fragment.config == null); assert(fragment.config == null);
children.addAll(fragment.compileChildren( return fragment.compileChildren(
parentSemanticsClipRect: parentSemanticsClipRect, parentSemanticsClipRect: parentSemanticsClipRect,
parentPaintClipRect: parentPaintClipRect, parentPaintClipRect: parentPaintClipRect,
elevationAdjustment: 0.0, elevationAdjustment: 0.0,
)); );
} })
.toList();
node.updateWith(config: null, childrenInInversePaintOrder: children); node.updateWith(config: null, childrenInInversePaintOrder: children);
// The root node is the only semantics node allowed to be invisible. This // The root node is the only semantics node allowed to be invisible. This
...@@ -3447,14 +3448,13 @@ class _SwitchableSemanticsFragment extends _InterestingSemanticsFragment { ...@@ -3447,14 +3448,13 @@ class _SwitchableSemanticsFragment extends _InterestingSemanticsFragment {
} }
} }
final List<SemanticsNode> children = <SemanticsNode>[]; final List<SemanticsNode> children = _children
for (_InterestingSemanticsFragment fragment in _children) { .expand((_InterestingSemanticsFragment fragment) => fragment.compileChildren(
children.addAll(fragment.compileChildren(
parentSemanticsClipRect: node.parentSemanticsClipRect, parentSemanticsClipRect: node.parentSemanticsClipRect,
parentPaintClipRect: node.parentPaintClipRect, parentPaintClipRect: node.parentPaintClipRect,
elevationAdjustment: 0.0, elevationAdjustment: 0.0,
)); ))
} .toList();
if (_config.isSemanticBoundary) { if (_config.isSemanticBoundary) {
owner.assembleSemanticsNode(node, _config, children); owner.assembleSemanticsNode(node, _config, children);
......
...@@ -421,14 +421,12 @@ class SliverConstraints extends Constraints { ...@@ -421,14 +421,12 @@ class SliverConstraints extends Constraints {
void verify(bool check, String message) { void verify(bool check, String message) {
if (check) if (check)
return; return;
final List<DiagnosticsNode> information = <DiagnosticsNode>[]; throw FlutterError.fromParts(<DiagnosticsNode>[
information.add(ErrorSummary('$runtimeType is not valid: $message')); ErrorSummary('$runtimeType is not valid: $message'),
if (informationCollector != null)
if (informationCollector != null) { ...informationCollector(),
information.addAll(informationCollector()); DiagnosticsProperty<SliverConstraints>('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty)
} ]);
information.add(DiagnosticsProperty<SliverConstraints>('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty));
throw FlutterError.fromParts(information);
} }
verify(axis != null, 'The "axis" is null.'); verify(axis != null, 'The "axis" is null.');
verify(growthDirection != null, 'The "growthDirection" is null.'); verify(growthDirection != null, 'The "growthDirection" is null.');
...@@ -700,15 +698,12 @@ class SliverGeometry extends Diagnosticable { ...@@ -700,15 +698,12 @@ class SliverGeometry extends Diagnosticable {
void verify(bool check, String summary, {List<DiagnosticsNode> details}) { void verify(bool check, String summary, {List<DiagnosticsNode> details}) {
if (check) if (check)
return; return;
final List<DiagnosticsNode> information = <DiagnosticsNode>[]; throw FlutterError.fromParts(<DiagnosticsNode>[
information.add(ErrorSummary('$runtimeType is not valid: $summary')); ErrorSummary('$runtimeType is not valid: $summary'),
if (details != null) { ...?details,
information.addAll(details); if (informationCollector != null)
} ...informationCollector(),
if (informationCollector != null) { ]);
information.addAll(informationCollector());
}
throw FlutterError.fromParts(information);
} }
verify(scrollExtent != null, 'The "scrollExtent" is null.'); verify(scrollExtent != null, 'The "scrollExtent" is null.');
......
...@@ -2280,12 +2280,9 @@ class _SemanticsSortGroup extends Comparable<_SemanticsSortGroup> { ...@@ -2280,12 +2280,9 @@ class _SemanticsSortGroup extends Comparable<_SemanticsSortGroup> {
horizontalGroups = horizontalGroups.reversed.toList(); horizontalGroups = horizontalGroups.reversed.toList();
} }
final List<SemanticsNode> result = <SemanticsNode>[]; return horizontalGroups
for (_SemanticsSortGroup group in horizontalGroups) { .expand((_SemanticsSortGroup group) => group.sortedWithinKnot())
final List<SemanticsNode> sortedKnotNodes = group.sortedWithinKnot(); .toList();
result.addAll(sortedKnotNodes);
}
return result;
} }
/// Sorts [nodes] where nodes intersect both vertically and horizontally. /// Sorts [nodes] where nodes intersect both vertically and horizontally.
...@@ -2423,12 +2420,9 @@ List<SemanticsNode> _childrenInDefaultOrder(List<SemanticsNode> children, TextDi ...@@ -2423,12 +2420,9 @@ List<SemanticsNode> _childrenInDefaultOrder(List<SemanticsNode> children, TextDi
} }
verticalGroups.sort(); verticalGroups.sort();
final List<SemanticsNode> result = <SemanticsNode>[]; return verticalGroups
for (_SemanticsSortGroup group in verticalGroups) { .expand((_SemanticsSortGroup group) => group.sortedWithinVerticalGroup())
final List<SemanticsNode> sortedGroupNodes = group.sortedWithinVerticalGroup(); .toList();
result.addAll(sortedGroupNodes);
}
return result;
} }
/// The implementation of [Comparable] that implements the ordering of /// The implementation of [Comparable] that implements the ordering of
......
...@@ -272,15 +272,15 @@ class NestedScrollView extends StatefulWidget { ...@@ -272,15 +272,15 @@ class NestedScrollView extends StatefulWidget {
} }
List<Widget> _buildSlivers(BuildContext context, ScrollController innerController, bool bodyIsScrolled) { List<Widget> _buildSlivers(BuildContext context, ScrollController innerController, bool bodyIsScrolled) {
final List<Widget> slivers = <Widget>[]; return <Widget>[
slivers.addAll(headerSliverBuilder(context, bodyIsScrolled)); ...headerSliverBuilder(context, bodyIsScrolled),
slivers.add(SliverFillRemaining( SliverFillRemaining(
child: PrimaryScrollController( child: PrimaryScrollController(
controller: innerController, controller: innerController,
child: body, child: body,
),
), ),
)); ];
return slivers;
} }
@override @override
......
...@@ -1534,14 +1534,13 @@ mixin WidgetInspectorService { ...@@ -1534,14 +1534,13 @@ mixin WidgetInspectorService {
List<DiagnosticsNode> nodes, List<DiagnosticsNode> nodes,
_SerializationDelegate delegate, _SerializationDelegate delegate,
) { ) {
final List<DiagnosticsNode> children = <DiagnosticsNode>[]; final List<DiagnosticsNode> children = <DiagnosticsNode>[
for (DiagnosticsNode child in nodes) { for (DiagnosticsNode child in nodes)
if (!delegate.summaryTree || _shouldShowInSummaryTree(child)) { if (!delegate.summaryTree || _shouldShowInSummaryTree(child))
children.add(child); child
} else { else
children.addAll(_getChildrenFiltered(child, delegate)); ..._getChildrenFiltered(child, delegate),
} ];
}
return children; return children;
} }
...@@ -2154,8 +2153,10 @@ class _WidgetInspectorState extends State<WidgetInspector> ...@@ -2154,8 +2153,10 @@ class _WidgetInspectorState extends State<WidgetInspector>
return size == null ? double.maxFinite : size.width * size.height; return size == null ? double.maxFinite : size.width * size.height;
} }
regularHits.sort((RenderObject a, RenderObject b) => _area(a).compareTo(_area(b))); regularHits.sort((RenderObject a, RenderObject b) => _area(a).compareTo(_area(b)));
final Set<RenderObject> hits = <RenderObject>{}; final Set<RenderObject> hits = <RenderObject>{
hits..addAll(edgeHits)..addAll(regularHits); ...edgeHits,
...regularHits,
};
return hits.toList(); return hits.toList();
} }
......
...@@ -174,11 +174,7 @@ void main() { ...@@ -174,11 +174,7 @@ void main() {
final Map<String, Object> result = testTree.toDiagnosticsNode().toJsonMap(TestDiagnosticsSerializationDelegate( final Map<String, Object> result = testTree.toDiagnosticsNode().toJsonMap(TestDiagnosticsSerializationDelegate(
subtreeDepth: 1, subtreeDepth: 1,
childFilter: (List<DiagnosticsNode> nodes, DiagnosticsNode owner) { childFilter: (List<DiagnosticsNode> nodes, DiagnosticsNode owner) {
final List<DiagnosticsNode> result = <DiagnosticsNode>[]; return nodes.expand((DiagnosticsNode node) => node.getChildren()).toList();
for (DiagnosticsNode node in nodes) {
result.addAll(node.getChildren());
}
return result;
} }
)); ));
final List<Map<String, Object>> children = result['children']; final List<Map<String, Object>> children = result['children'];
......
...@@ -260,13 +260,13 @@ void main() { ...@@ -260,13 +260,13 @@ void main() {
expect(paragraph.size.height, 26.0); expect(paragraph.size.height, 26.0);
// Test the sizes of nested spans. // Test the sizes of nested spans.
final List<ui.TextBox> boxes = <ui.TextBox>[];
final String text = testSpan.toStringDeep(); final String text = testSpan.toStringDeep();
for (int i = 0; i < text.length; ++i) { final List<ui.TextBox> boxes = <ui.TextBox>[
boxes.addAll(paragraph.getBoxesForSelection( for (int i = 0; i < text.length; ++i)
...paragraph.getBoxesForSelection(
TextSelection(baseOffset: i, extentOffset: i + 1) TextSelection(baseOffset: i, extentOffset: i + 1)
)); ),
} ];
expect(boxes.length, equals(4)); expect(boxes.length, equals(4));
// anyOf is needed here and below because Linux and Mac have different text // anyOf is needed here and below because Linux and Mac have different text
......
...@@ -836,15 +836,11 @@ class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding { ...@@ -836,15 +836,11 @@ class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
_allowedAssetKeys = <String>{}; _allowedAssetKeys = <String>{};
return; return;
} }
final Map<String, dynamic> manifest = json.decode( final Map<String, dynamic> manifest = json.decode(manifestFile.readAsStringSync());
manifestFile.readAsStringSync());
_allowedAssetKeys = <String>{ _allowedAssetKeys = <String>{
'AssetManifest.json', 'AssetManifest.json',
...manifest.values.cast<List<dynamic>>().expand<dynamic>((List<dynamic> e) => e).cast<String>(),
}; };
for (List<dynamic> value in manifest.values) {
final List<String> strList = List<String>.from(value);
_allowedAssetKeys.addAll(strList);
}
} }
@override @override
......
...@@ -2,7 +2,7 @@ name: flutter_test ...@@ -2,7 +2,7 @@ name: flutter_test
environment: environment:
# The pub client defaults to an <2.0.0 sdk constraint which we need to explicitly overwrite. # The pub client defaults to an <2.0.0 sdk constraint which we need to explicitly overwrite.
sdk: ">=2.2.0 <3.0.0" sdk: ">=2.2.2 <3.0.0"
dependencies: dependencies:
# To update these, use "flutter update-packages --force-upgrade". # To update these, use "flutter update-packages --force-upgrade".
......
...@@ -72,6 +72,7 @@ Future<void> main(List<String> args) async { ...@@ -72,6 +72,7 @@ Future<void> main(List<String> args) async {
// Otherwise assume the package is flat. // Otherwise assume the package is flat.
targetFile = entrypoint; targetFile = entrypoint;
} }
final String deviceName = argResults['device'];
final List<String> command = <String>[ final List<String> command = <String>[
'attach', 'attach',
'--module', '--module',
...@@ -86,14 +87,9 @@ Future<void> main(List<String> args) async { ...@@ -86,14 +87,9 @@ Future<void> main(List<String> args) async {
outputDill, outputDill,
'--packages', '--packages',
packages, packages,
if (deviceName != null && deviceName.isNotEmpty) ...<String>['-d', deviceName],
if (verbose) '--verbose',
]; ];
final String deviceName = argResults['device'];
if (deviceName != null && deviceName.isNotEmpty) {
command.addAll(<String>['-d', deviceName]);
}
if (verbose) {
command.add('--verbose');
}
Cache.disableLocking(); // ignore: invalid_use_of_visible_for_testing_member Cache.disableLocking(); // ignore: invalid_use_of_visible_for_testing_member
await runner.run( await runner.run(
command, command,
......
...@@ -520,40 +520,40 @@ class AndroidDevice extends Device { ...@@ -520,40 +520,40 @@ class AndroidDevice extends Device {
'-f', '0x20000000', // FLAG_ACTIVITY_SINGLE_TOP '-f', '0x20000000', // FLAG_ACTIVITY_SINGLE_TOP
'--ez', 'enable-background-compilation', 'true', '--ez', 'enable-background-compilation', 'true',
'--ez', 'enable-dart-profiling', 'true', '--ez', 'enable-dart-profiling', 'true',
if (traceStartup)
...<String>['--ez', 'trace-startup', 'true'],
if (route != null)
...<String>['--es', 'route', route],
if (debuggingOptions.enableSoftwareRendering)
...<String>['--ez', 'enable-software-rendering', 'true'],
if (debuggingOptions.skiaDeterministicRendering)
...<String>['--ez', 'skia-deterministic-rendering', 'true'],
if (debuggingOptions.traceSkia)
...<String>['--ez', 'trace-skia', 'true'],
if (debuggingOptions.traceSystrace)
...<String>['--ez', 'trace-systrace', 'true'],
if (debuggingOptions.dumpSkpOnShaderCompilation)
...<String>['--ez', 'dump-skp-on-shader-compilation', 'true'],
if (debuggingOptions.debuggingEnabled)
...<String>[
if (debuggingOptions.buildInfo.isDebug)
...<String>[
...<String>['--ez', 'enable-checked-mode', 'true'],
...<String>['--ez', 'verify-entry-points', 'true'],
],
if (debuggingOptions.startPaused)
...<String>['--ez', 'start-paused', 'true'],
if (debuggingOptions.disableServiceAuthCodes)
...<String>['--ez', 'disable-service-auth-codes', 'true'],
if (debuggingOptions.dartFlags.isNotEmpty)
...<String>['--es', 'dart-flags', debuggingOptions.dartFlags],
if (debuggingOptions.useTestFonts)
...<String>['--ez', 'use-test-fonts', 'true'],
if (debuggingOptions.verboseSystemLogs)
...<String>['--ez', 'verbose-logging', 'true'],
],
apk.launchActivity,
]; ];
if (traceStartup)
cmd.addAll(<String>['--ez', 'trace-startup', 'true']);
if (route != null)
cmd.addAll(<String>['--es', 'route', route]);
if (debuggingOptions.enableSoftwareRendering)
cmd.addAll(<String>['--ez', 'enable-software-rendering', 'true']);
if (debuggingOptions.skiaDeterministicRendering)
cmd.addAll(<String>['--ez', 'skia-deterministic-rendering', 'true']);
if (debuggingOptions.traceSkia)
cmd.addAll(<String>['--ez', 'trace-skia', 'true']);
if (debuggingOptions.traceSystrace)
cmd.addAll(<String>['--ez', 'trace-systrace', 'true']);
if (debuggingOptions.dumpSkpOnShaderCompilation)
cmd.addAll(<String>['--ez', 'dump-skp-on-shader-compilation', 'true']);
if (debuggingOptions.debuggingEnabled) {
if (debuggingOptions.buildInfo.isDebug) {
cmd.addAll(<String>['--ez', 'enable-checked-mode', 'true']);
cmd.addAll(<String>['--ez', 'verify-entry-points', 'true']);
}
if (debuggingOptions.startPaused)
cmd.addAll(<String>['--ez', 'start-paused', 'true']);
if (debuggingOptions.disableServiceAuthCodes)
cmd.addAll(<String>['--ez', 'disable-service-auth-codes', 'true']);
if (debuggingOptions.dartFlags.isNotEmpty)
cmd.addAll(<String>['--es', 'dart-flags', debuggingOptions.dartFlags]);
if (debuggingOptions.useTestFonts)
cmd.addAll(<String>['--ez', 'use-test-fonts', 'true']);
if (debuggingOptions.verboseSystemLogs) {
cmd.addAll(<String>['--ez', 'verbose-logging', 'true']);
}
}
cmd.add(apk.launchActivity);
final String result = (await runAdbCheckedAsync(cmd)).stdout; final String result = (await runAdbCheckedAsync(cmd)).stdout;
// This invocation returns 0 even when it fails. // This invocation returns 0 even when it fails.
if (result.contains('Error: ')) { if (result.contains('Error: ')) {
......
...@@ -17,15 +17,13 @@ class AndroidStudioValidator extends DoctorValidator { ...@@ -17,15 +17,13 @@ class AndroidStudioValidator extends DoctorValidator {
final AndroidStudio _studio; final AndroidStudio _studio;
static List<DoctorValidator> get allValidators { static List<DoctorValidator> get allValidators {
final List<DoctorValidator> validators = <DoctorValidator>[];
final List<AndroidStudio> studios = AndroidStudio.allInstalled(); final List<AndroidStudio> studios = AndroidStudio.allInstalled();
if (studios.isEmpty) { return <DoctorValidator>[
validators.add(NoAndroidStudioValidator()); if (studios.isEmpty)
} else { NoAndroidStudioValidator()
validators.addAll(studios else
.map<DoctorValidator>((AndroidStudio studio) => AndroidStudioValidator(studio))); ...studios.map<DoctorValidator>((AndroidStudio studio) => AndroidStudioValidator(studio))
} ];
return validators;
} }
@override @override
......
...@@ -216,10 +216,10 @@ class _ManifestAssetBundle implements AssetBundle { ...@@ -216,10 +216,10 @@ class _ManifestAssetBundle implements AssetBundle {
} }
} }
final List<_Asset> materialAssets = <_Asset>[]; final List<_Asset> materialAssets = <_Asset>[
if (flutterManifest.usesMaterialDesign && includeDefaultFonts) { if (flutterManifest.usesMaterialDesign && includeDefaultFonts)
materialAssets.addAll(_getMaterialAssets(_fontSetMaterial)); ..._getMaterialAssets(_fontSetMaterial),
} ];
for (_Asset asset in materialAssets) { for (_Asset asset in materialAssets) {
assert(asset.assetFileExists); assert(asset.assetFileExists);
entries[asset.entryUri.path] ??= DevFSFileContent(asset.assetFile); entries[asset.entryUri.path] ??= DevFSFileContent(asset.assetFile);
...@@ -421,20 +421,18 @@ List<Map<String, dynamic>> _parseFonts( ...@@ -421,20 +421,18 @@ List<Map<String, dynamic>> _parseFonts(
PackageMap packageMap, { PackageMap packageMap, {
String packageName, String packageName,
}) { }) {
final List<Map<String, dynamic>> fonts = <Map<String, dynamic>>[]; return <Map<String, dynamic>>[
if (manifest.usesMaterialDesign && includeDefaultFonts) { if (manifest.usesMaterialDesign && includeDefaultFonts)
fonts.addAll(_getMaterialFonts(_ManifestAssetBundle._fontSetMaterial)); ..._getMaterialFonts(_ManifestAssetBundle._fontSetMaterial),
} if (packageName == null)
if (packageName == null) { ...manifest.fontsDescriptor
fonts.addAll(manifest.fontsDescriptor); else
} else { ..._createFontsDescriptor(_parsePackageFonts(
fonts.addAll(_createFontsDescriptor(_parsePackageFonts( manifest,
manifest, packageName,
packageName, packageMap,
packageMap, )),
))); ];
}
return fonts;
} }
/// Prefixes family names and asset paths of fonts included from packages with /// Prefixes family names and asset paths of fonts included from packages with
......
...@@ -228,7 +228,7 @@ class AOTSnapshotter { ...@@ -228,7 +228,7 @@ class AOTSnapshotter {
final List<String> commonBuildOptions = <String>['-arch', targetArch, '-miphoneos-version-min=8.0']; final List<String> commonBuildOptions = <String>['-arch', targetArch, '-miphoneos-version-min=8.0'];
final String assemblyO = fs.path.join(outputPath, 'snapshot_assembly.o'); final String assemblyO = fs.path.join(outputPath, 'snapshot_assembly.o');
final RunResult compileResult = await xcode.cc(commonBuildOptions.toList()..addAll(<String>['-c', assemblyPath, '-o', assemblyO])); final RunResult compileResult = await xcode.cc(<String>[...commonBuildOptions, '-c', assemblyPath, '-o', assemblyO]);
if (compileResult.exitCode != 0) { if (compileResult.exitCode != 0) {
printError('Failed to compile AOT snapshot. Compiler terminated with exit code ${compileResult.exitCode}'); printError('Failed to compile AOT snapshot. Compiler terminated with exit code ${compileResult.exitCode}');
return compileResult; return compileResult;
...@@ -237,14 +237,15 @@ class AOTSnapshotter { ...@@ -237,14 +237,15 @@ class AOTSnapshotter {
final String frameworkDir = fs.path.join(outputPath, 'App.framework'); final String frameworkDir = fs.path.join(outputPath, 'App.framework');
fs.directory(frameworkDir).createSync(recursive: true); fs.directory(frameworkDir).createSync(recursive: true);
final String appLib = fs.path.join(frameworkDir, 'App'); final String appLib = fs.path.join(frameworkDir, 'App');
final List<String> linkArgs = commonBuildOptions.toList()..addAll(<String>[ final List<String> linkArgs = <String>[
'-dynamiclib', ...commonBuildOptions,
'-Xlinker', '-rpath', '-Xlinker', '@executable_path/Frameworks', '-dynamiclib',
'-Xlinker', '-rpath', '-Xlinker', '@loader_path/Frameworks', '-Xlinker', '-rpath', '-Xlinker', '@executable_path/Frameworks',
'-install_name', '@rpath/App.framework/App', '-Xlinker', '-rpath', '-Xlinker', '@loader_path/Frameworks',
'-o', appLib, '-install_name', '@rpath/App.framework/App',
assemblyO, '-o', appLib,
]); assemblyO,
];
final RunResult linkResult = await xcode.clang(linkArgs); final RunResult linkResult = await xcode.clang(linkArgs);
if (linkResult.exitCode != 0) { if (linkResult.exitCode != 0) {
printError('Failed to link AOT snapshot. Linker terminated with exit code ${compileResult.exitCode}'); printError('Failed to link AOT snapshot. Linker terminated with exit code ${compileResult.exitCode}');
...@@ -371,8 +372,10 @@ class JITSnapshotter { ...@@ -371,8 +372,10 @@ class JITSnapshotter {
genSnapshotArgs.addAll(extraGenSnapshotOptions); genSnapshotArgs.addAll(extraGenSnapshotOptions);
} }
final Set<String> outputPaths = <String>{}; final Set<String> outputPaths = <String>{
outputPaths.addAll(<String>[isolateSnapshotData, isolateSnapshotInstructions]); isolateSnapshotData,
isolateSnapshotInstructions,
};
// There are a couple special cases below where we create a snapshot // There are a couple special cases below where we create a snapshot
// with only the data section, which only contains interpreted code. // with only the data section, which only contains interpreted code.
......
...@@ -94,9 +94,11 @@ class Fingerprinter { ...@@ -94,9 +94,11 @@ class Fingerprinter {
} }
Future<List<String>> _getPaths() async { Future<List<String>> _getPaths() async {
final Set<String> paths = _paths.toSet(); final Set<String> paths = <String>{
for (String depfilePath in _depfilePaths) ..._paths,
paths.addAll(await readDepfile(depfilePath)); for (String depfilePath in _depfilePaths)
...await readDepfile(depfilePath),
};
final FingerprintPathFilter filter = _pathFilter ?? (String path) => true; final FingerprintPathFilter filter = _pathFilter ?? (String path) => true;
return paths.where(filter).toList()..sort(); return paths.where(filter).toList()..sort();
} }
...@@ -118,7 +120,7 @@ class Fingerprint { ...@@ -118,7 +120,7 @@ class Fingerprint {
final List<int> bytes = file.readAsBytesSync(); final List<int> bytes = file.readAsBytesSync();
_checksums[file.path] = md5.convert(bytes).toString(); _checksums[file.path] = md5.convert(bytes).toString();
} }
_properties = <String, String>{}..addAll(properties); _properties = <String, String>{...properties};
} }
/// Creates a Fingerprint from serialized JSON. /// Creates a Fingerprint from serialized JSON.
......
...@@ -637,30 +637,22 @@ class FlutterSdk extends EngineCachedArtifact { ...@@ -637,30 +637,22 @@ class FlutterSdk extends EngineCachedArtifact {
@override @override
List<List<String>> getBinaryDirs() { List<List<String>> getBinaryDirs() {
final List<List<String>> binaryDirs = <List<String>>[ return <List<String>>[
<String>['common', 'flutter_patched_sdk.zip'], <String>['common', 'flutter_patched_sdk.zip'],
<String>['common', 'flutter_patched_sdk_product.zip'], <String>['common', 'flutter_patched_sdk_product.zip'],
]; if (cache.includeAllPlatforms)
if (cache.includeAllPlatforms) { ...<List<String>>[
binaryDirs.addAll(<List<String>>[ <String>['windows-x64', 'windows-x64/artifacts.zip'],
<String>['windows-x64', 'windows-x64/artifacts.zip'], <String>['linux-x64', 'linux-x64/artifacts.zip'],
<String>['linux-x64', 'linux-x64/artifacts.zip'], <String>['darwin-x64', 'darwin-x64/artifacts.zip'],
<String>['darwin-x64', 'darwin-x64/artifacts.zip'], ]
]); else if (platform.isWindows)
} else if (platform.isWindows) { <String>['windows-x64', 'windows-x64/artifacts.zip']
binaryDirs.addAll(<List<String>>[ else if (platform.isMacOS)
<String>['windows-x64', 'windows-x64/artifacts.zip'], <String>['darwin-x64', 'darwin-x64/artifacts.zip']
]); else if (platform.isLinux)
} else if (platform.isMacOS) {
binaryDirs.addAll(<List<String>>[
<String>['darwin-x64', 'darwin-x64/artifacts.zip'],
]);
} else if (platform.isLinux) {
binaryDirs.addAll(<List<String>>[
<String>['linux-x64', 'linux-x64/artifacts.zip'], <String>['linux-x64', 'linux-x64/artifacts.zip'],
]); ];
}
return binaryDirs;
} }
@override @override
...@@ -745,28 +737,31 @@ class AndroidEngineArtifacts extends EngineCachedArtifact { ...@@ -745,28 +737,31 @@ class AndroidEngineArtifacts extends EngineCachedArtifact {
@override @override
List<List<String>> getBinaryDirs() { List<List<String>> getBinaryDirs() {
final List<List<String>> binaryDirs = <List<String>>[]; return <List<String>>[
if (cache.includeAllPlatforms) { if (cache.includeAllPlatforms)
binaryDirs ...<List<String>>[
..addAll(_osxBinaryDirs) ..._osxBinaryDirs,
..addAll(_linuxBinaryDirs) ..._linuxBinaryDirs,
..addAll(_windowsBinaryDirs) ..._windowsBinaryDirs,
..addAll(_androidBinaryDirs) ..._androidBinaryDirs,
..addAll(_dartSdks); ..._dartSdks,
} else if (platform.isWindows) { ]
binaryDirs else if (platform.isWindows)
..addAll(_windowsBinaryDirs) ...<List<String>>[
..addAll(_androidBinaryDirs); ..._windowsBinaryDirs,
} else if (platform.isMacOS) { ..._androidBinaryDirs,
binaryDirs ]
..addAll(_osxBinaryDirs) else if (platform.isMacOS)
..addAll(_androidBinaryDirs); ...<List<String>>[
} else if (platform.isLinux) { ..._osxBinaryDirs,
binaryDirs ..._androidBinaryDirs,
..addAll(_linuxBinaryDirs) ]
..addAll(_androidBinaryDirs); else if (platform.isLinux)
} ...<List<String>>[
return binaryDirs; ..._linuxBinaryDirs,
..._androidBinaryDirs,
]
];
} }
@override @override
...@@ -782,11 +777,10 @@ class IOSEngineArtifacts extends EngineCachedArtifact { ...@@ -782,11 +777,10 @@ class IOSEngineArtifacts extends EngineCachedArtifact {
@override @override
List<List<String>> getBinaryDirs() { List<List<String>> getBinaryDirs() {
final List<List<String>> binaryDirs = <List<String>>[]; return <List<String>>[
if (platform.isMacOS || cache.includeAllPlatforms) { if (platform.isMacOS || cache.includeAllPlatforms)
binaryDirs.addAll(_iosBinaryDirs); ..._iosBinaryDirs,
} ];
return binaryDirs;
} }
@override @override
...@@ -914,10 +908,10 @@ final Map<int, List<int>> _flattenNameSubstitutions = <int, List<int>>{ ...@@ -914,10 +908,10 @@ final Map<int, List<int>> _flattenNameSubstitutions = <int, List<int>>{
/// Given a name containing slashes, colons, and backslashes, expand it into /// Given a name containing slashes, colons, and backslashes, expand it into
/// something that doesn't. /// something that doesn't.
String _flattenNameNoSubdirs(String fileName) { String _flattenNameNoSubdirs(String fileName) {
final List<int> replacedCodeUnits = <int>[]; final List<int> replacedCodeUnits = <int>[
for (int codeUnit in fileName.codeUnits) { for (int codeUnit in fileName.codeUnits)
replacedCodeUnits.addAll(_flattenNameSubstitutions[codeUnit] ?? <int>[codeUnit]); ..._flattenNameSubstitutions[codeUnit] ?? <int>[codeUnit],
} ];
return String.fromCharCodes(replacedCodeUnits); return String.fromCharCodes(replacedCodeUnits);
} }
......
...@@ -618,10 +618,10 @@ class AppDomain extends Domain { ...@@ -618,10 +618,10 @@ class AppDomain extends Domain {
} }
void _sendAppEvent(AppInstance app, String name, [ Map<String, dynamic> args ]) { void _sendAppEvent(AppInstance app, String name, [ Map<String, dynamic> args ]) {
final Map<String, dynamic> eventArgs = <String, dynamic>{'appId': app.id}; sendEvent('app.$name', <String, dynamic>{
if (args != null) 'appId': app.id,
eventArgs.addAll(args); ...?args,
sendEvent('app.$name', eventArgs); });
} }
} }
......
...@@ -61,23 +61,14 @@ class FormatCommand extends FlutterCommand { ...@@ -61,23 +61,14 @@ class FormatCommand extends FlutterCommand {
} }
final String dartfmt = sdkBinaryName('dartfmt'); final String dartfmt = sdkBinaryName('dartfmt');
final List<String> command = <String>[dartfmt]; final List<String> command = <String>[
dartfmt,
if (argResults['dry-run']) { if (argResults['dry-run']) '-n',
command.add('-n'); if (argResults['machine']) '-m',
} if (!argResults['dry-run'] && !argResults['machine']) '-w',
if (argResults['machine']) { if (argResults['set-exit-if-changed']) '--set-exit-if-changed',
command.add('-m'); ...argResults.rest,
} ];
if (!argResults['dry-run'] && !argResults['machine']) {
command.add('-w');
}
if (argResults['set-exit-if-changed']) {
command.add('--set-exit-if-changed');
}
command..addAll(argResults.rest);
final int result = await runCommandAndStreamOutput(command); final int result = await runCommandAndStreamOutput(command);
if (result != 0) if (result != 0)
......
...@@ -179,15 +179,13 @@ class TestCommand extends FastFlutterCommand { ...@@ -179,15 +179,13 @@ class TestCommand extends FastFlutterCommand {
); );
} }
} else { } else {
final List<String> fileCopy = <String>[]; files = <String>[
for (String file in files) { for (String file in files)
if (file.endsWith(platform.pathSeparator)) { if (file.endsWith(platform.pathSeparator))
fileCopy.addAll(_findTests(fs.directory(file))); ..._findTests(fs.directory(file))
} else { else
fileCopy.add(file); file
} ];
}
files = fileCopy;
} }
CoverageCollector collector; CoverageCollector collector;
......
...@@ -728,9 +728,11 @@ class PubspecYaml { ...@@ -728,9 +728,11 @@ class PubspecYaml {
// Merge the lists of dependencies we've seen in this file from dependencies, dev dependencies, // Merge the lists of dependencies we've seen in this file from dependencies, dev dependencies,
// and the dependencies we know this file mentions that are already pinned // and the dependencies we know this file mentions that are already pinned
// (and which didn't get special processing above). // (and which didn't get special processing above).
final Set<String> implied = Set<String>.from(directDependencies) final Set<String> implied = <String>{
..addAll(specialDependencies) ...directDependencies,
..addAll(devDependencies); ...specialDependencies,
...devDependencies,
};
// Create a new set to hold the list of packages we've already processed, so // Create a new set to hold the list of packages we've already processed, so
// that we don't redundantly process them multiple times. // that we don't redundantly process them multiple times.
...@@ -751,12 +753,12 @@ class PubspecYaml { ...@@ -751,12 +753,12 @@ class PubspecYaml {
transitiveDevDependencyOutput.add(' $package: ${versions.versionFor(package)} $kTransitiveMagicString'); transitiveDevDependencyOutput.add(' $package: ${versions.versionFor(package)} $kTransitiveMagicString');
// Build a sorted list of all dependencies for the checksum. // Build a sorted list of all dependencies for the checksum.
final Set<String> checksumDependencies = <String>{} final Set<String> checksumDependencies = <String>{
..addAll(directDependencies) ...directDependencies,
..addAll(devDependencies) ...devDependencies,
..addAll(transitiveDependenciesAsList) ...transitiveDependenciesAsList,
..addAll(transitiveDevDependenciesAsList); ...transitiveDevDependenciesAsList,
checksumDependencies.removeAll(specialDependencies); }..removeAll(specialDependencies);
// Add a blank line before and after each section to keep the resulting output clean. // Add a blank line before and after each section to keep the resulting output clean.
transitiveDependencyOutput transitiveDependencyOutput
......
...@@ -96,12 +96,12 @@ Future<void> pubGet({ ...@@ -96,12 +96,12 @@ Future<void> pubGet({
'Running "flutter pub $command" in ${fs.path.basename(directory)}...', 'Running "flutter pub $command" in ${fs.path.basename(directory)}...',
timeout: timeoutConfiguration.slowOperation, timeout: timeoutConfiguration.slowOperation,
); );
final List<String> args = <String>['--verbosity=warning']; final List<String> args = <String>[
if (FlutterCommand.current != null && FlutterCommand.current.globalResults['verbose']) '--verbosity=warning',
args.add('--verbose'); if (FlutterCommand.current != null && FlutterCommand.current.globalResults['verbose']) '--verbose',
args.addAll(<String>[command, '--no-precompile']); ...<String>[command, '--no-precompile'],
if (offline) if (offline) '--offline',
args.add('--offline'); ];
try { try {
await pub( await pub(
args, args,
...@@ -228,21 +228,13 @@ const String _pubCacheEnvironmentKey = 'PUB_CACHE'; ...@@ -228,21 +228,13 @@ const String _pubCacheEnvironmentKey = 'PUB_CACHE';
String _getPubEnvironmentValue(PubContext pubContext) { String _getPubEnvironmentValue(PubContext pubContext) {
// DO NOT update this function without contacting kevmoo. // DO NOT update this function without contacting kevmoo.
// We have server-side tooling that assumes the values are consistent. // We have server-side tooling that assumes the values are consistent.
final List<String> values = <String>[];
final String existing = platform.environment[_pubEnvironmentKey]; final String existing = platform.environment[_pubEnvironmentKey];
final List<String> values = <String>[
if ((existing != null) && existing.isNotEmpty) { if (existing != null && existing.isNotEmpty) existing,
values.add(existing); if (isRunningOnBot) 'flutter_bot',
} 'flutter_cli',
...pubContext._values,
if (isRunningOnBot) { ];
values.add('flutter_bot');
}
values.add('flutter_cli');
values.addAll(pubContext._values);
return values.join(':'); return values.join(':');
} }
......
...@@ -161,11 +161,10 @@ class DeviceManager { ...@@ -161,11 +161,10 @@ class DeviceManager {
/// Get diagnostics about issues with any connected devices. /// Get diagnostics about issues with any connected devices.
Future<List<String>> getDeviceDiagnostics() async { Future<List<String>> getDeviceDiagnostics() async {
final List<String> diagnostics = <String>[]; return <String>[
for (DeviceDiscovery discoverer in _platformDiscoverers) { for (DeviceDiscovery discoverer in _platformDiscoverers)
diagnostics.addAll(await discoverer.getDiagnostics()); ...await discoverer.getDiagnostics(),
} ];
return diagnostics;
} }
/// Find and return a list of devices based on the current project and environment. /// Find and return a list of devices based on the current project and environment.
......
...@@ -60,45 +60,37 @@ class _DefaultDoctorValidatorsProvider implements DoctorValidatorsProvider { ...@@ -60,45 +60,37 @@ class _DefaultDoctorValidatorsProvider implements DoctorValidatorsProvider {
@override @override
List<DoctorValidator> get validators { List<DoctorValidator> get validators {
if (_validators == null) { if (_validators == null) {
_validators = <DoctorValidator>[]; final List<DoctorValidator> ideValidators = <DoctorValidator>[
_validators.add(FlutterValidator()); ...AndroidStudioValidator.allValidators,
...IntelliJValidator.installedValidators,
if (androidWorkflow.appliesToHostPlatform) ...VsCodeValidator.installedValidators,
_validators.add(GroupedValidator(<DoctorValidator>[androidValidator, androidLicenseValidator])); ];
if (iosWorkflow.appliesToHostPlatform || macOSWorkflow.appliesToHostPlatform) _validators = <DoctorValidator>[
_validators.add(GroupedValidator(<DoctorValidator>[xcodeValidator, cocoapodsValidator])); FlutterValidator(),
if (androidWorkflow.appliesToHostPlatform)
if (iosWorkflow.appliesToHostPlatform) GroupedValidator(<DoctorValidator>[androidValidator, androidLicenseValidator]),
_validators.add(iosValidator); if (iosWorkflow.appliesToHostPlatform || macOSWorkflow.appliesToHostPlatform)
GroupedValidator(<DoctorValidator>[xcodeValidator, cocoapodsValidator]),
if (webWorkflow.appliesToHostPlatform) if (iosWorkflow.appliesToHostPlatform)
_validators.add(const WebValidator()); iosValidator,
if (webWorkflow.appliesToHostPlatform)
// Add desktop doctors to workflow if the flag is enabled. const WebValidator(),
if (flutterDesktopEnabled) { // Add desktop doctors to workflow if the flag is enabled.
if (linuxWorkflow.appliesToHostPlatform) { if (flutterDesktopEnabled)
_validators.add(LinuxDoctorValidator()); ...<DoctorValidator>[
} if (linuxWorkflow.appliesToHostPlatform) LinuxDoctorValidator(),
if (windowsWorkflow.appliesToHostPlatform) { if (windowsWorkflow.appliesToHostPlatform) visualStudioValidator,
_validators.add(visualStudioValidator); ],
} if (ideValidators.isNotEmpty)
} ...ideValidators
else
final List<DoctorValidator> ideValidators = <DoctorValidator>[]; NoIdeValidator(),
ideValidators.addAll(AndroidStudioValidator.allValidators); if (ProxyValidator.shouldShow)
ideValidators.addAll(IntelliJValidator.installedValidators); ProxyValidator(),
ideValidators.addAll(VsCodeValidator.installedValidators); if (deviceManager.canListAnything)
if (ideValidators.isNotEmpty) DeviceValidator(),
_validators.addAll(ideValidators); ];
else
_validators.add(NoIdeValidator());
if (ProxyValidator.shouldShow)
_validators.add(ProxyValidator());
if (deviceManager.canListAnything)
_validators.add(DeviceValidator());
} }
return _validators; return _validators;
} }
......
...@@ -144,12 +144,16 @@ class SimControl { ...@@ -144,12 +144,16 @@ class SimControl {
} }
Future<RunResult> launch(String deviceId, String appIdentifier, [ List<String> launchArgs ]) { Future<RunResult> launch(String deviceId, String appIdentifier, [ List<String> launchArgs ]) {
final List<String> args = <String>[_xcrunPath, 'simctl', 'launch', deviceId, appIdentifier];
if (launchArgs != null)
args.addAll(launchArgs);
Future<RunResult> result; Future<RunResult> result;
try { try {
result = runCheckedAsync(args); result = runCheckedAsync(<String>[
_xcrunPath,
'simctl',
'launch',
deviceId,
appIdentifier,
...?launchArgs,
]);
} on ProcessException catch (exception) { } on ProcessException catch (exception) {
throwToolExit('Unable to launch $appIdentifier on $deviceId:\n$exception'); throwToolExit('Unable to launch $appIdentifier on $deviceId:\n$exception');
} }
......
...@@ -407,12 +407,10 @@ abstract class FlutterCommand extends Command<void> { ...@@ -407,12 +407,10 @@ abstract class FlutterCommand extends Command<void> {
} }
// Send screen. // Send screen.
final Map<String, String> additionalUsageValues = <String, String>{};
final Map<String, String> currentUsageValues = await usageValues; final Map<String, String> currentUsageValues = await usageValues;
final Map<String, String> additionalUsageValues = <String, String>{
if (currentUsageValues != null) { ...?currentUsageValues,
additionalUsageValues.addAll(currentUsageValues); };
}
if (commandResult != null) { if (commandResult != null) {
switch (commandResult.exitStatus) { switch (commandResult.exitStatus) {
case ExitStatus.success: case ExitStatus.success:
...@@ -429,11 +427,12 @@ abstract class FlutterCommand extends Command<void> { ...@@ -429,11 +427,12 @@ abstract class FlutterCommand extends Command<void> {
flutterUsage.sendCommand(commandPath, parameters: additionalUsageValues); flutterUsage.sendCommand(commandPath, parameters: additionalUsageValues);
// Send timing. // Send timing.
final List<String> labels = <String>[]; final List<String> labels = <String>[
if (commandResult?.exitStatus != null) if (commandResult?.exitStatus != null)
labels.add(getEnumName(commandResult.exitStatus)); getEnumName(commandResult.exitStatus),
if (commandResult?.timingLabelParts?.isNotEmpty ?? false) if (commandResult?.timingLabelParts?.isNotEmpty ?? false)
labels.addAll(commandResult.timingLabelParts); ...commandResult.timingLabelParts,
];
final String label = labels final String label = labels
.where((String label) => !isBlank(label)) .where((String label) => !isBlank(label))
......
...@@ -47,26 +47,19 @@ Future<int> runTests( ...@@ -47,26 +47,19 @@ Future<int> runTests(
bool web = false, bool web = false,
}) async { }) async {
// Compute the command-line arguments for package:test. // Compute the command-line arguments for package:test.
final List<String> testArgs = <String>[]; final List<String> testArgs = <String>[
if (!terminal.supportsColor) { if (!terminal.supportsColor)
testArgs.addAll(<String>['--no-color']); '--no-color',
} if (machine)
...<String>['-r', 'json']
if (machine) { else
testArgs.addAll(<String>['-r', 'json']); ...<String>['-r', 'compact'],
} else { '--concurrency=$concurrency',
testArgs.addAll(<String>['-r', 'compact']); for (String name in names)
} ...<String>['--name', name],
for (String plainName in plainNames)
testArgs.add('--concurrency=$concurrency'); ...<String>['--plain-name', plainName],
];
for (String name in names) {
testArgs..add('--name')..add(name);
}
for (String plainName in plainNames) {
testArgs..add('--plain-name')..add(plainName);
}
if (web) { if (web) {
final String tempBuildDir = fs.systemTempDirectory final String tempBuildDir = fs.systemTempDirectory
.createTempSync('_flutter_test') .createTempSync('_flutter_test')
...@@ -80,10 +73,11 @@ Future<int> runTests( ...@@ -80,10 +73,11 @@ Future<int> runTests(
if (!result) { if (!result) {
throwToolExit('Failed to compile tests'); throwToolExit('Failed to compile tests');
} }
testArgs.add('--platform=chrome'); testArgs
testArgs.add('--precompiled=$tempBuildDir'); ..add('--platform=chrome')
testArgs.add('--'); ..add('--precompiled=$tempBuildDir')
testArgs.addAll(testFiles); ..add('--')
..addAll(testFiles);
hack.registerPlatformPlugin( hack.registerPlatformPlugin(
<Runtime>[Runtime.chrome], <Runtime>[Runtime.chrome],
() { () {
...@@ -94,8 +88,9 @@ Future<int> runTests( ...@@ -94,8 +88,9 @@ Future<int> runTests(
return exitCode; return exitCode;
} }
testArgs.add('--'); testArgs
testArgs.addAll(testFiles); ..add('--')
..addAll(testFiles);
// Configure package:test to use the Flutter engine for child processes. // Configure package:test to use the Flutter engine for child processes.
final String shellPath = artifacts.getArtifactPath(Artifact.flutterTester); final String shellPath = artifacts.getArtifactPath(Artifact.flutterTester);
......
...@@ -133,12 +133,15 @@ class FlutterVersion { ...@@ -133,12 +133,15 @@ class FlutterVersion {
String get frameworkCommitDate => _latestGitCommitDate(); String get frameworkCommitDate => _latestGitCommitDate();
static String _latestGitCommitDate([ String branch ]) { static String _latestGitCommitDate([ String branch ]) {
final List<String> args = <String>['git', 'log']; final List<String> args = <String>[
'git',
if (branch != null) 'log',
args.add(branch); if (branch != null) branch,
'-n',
args.addAll(<String>['-n', '1', '--pretty=format:%ad', '--date=iso']); '1',
'--pretty=format:%ad',
'--date=iso',
];
return _runSync(args, lenient: false); return _runSync(args, lenient: false);
} }
......
...@@ -211,7 +211,8 @@ void main() { ...@@ -211,7 +211,8 @@ void main() {
expect(await fingerprinter.doesFingerprintMatch(), isFalse); expect(await fingerprinter.doesFingerprintMatch(), isFalse);
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
Platform: () => mockPlatformDisabledCache, Platform: () => mockPlatformDisabledCache,
}..addAll(contextOverrides)); ...contextOverrides,
});
final Platform mockPlatformEnabledCache = MockPlatform(); final Platform mockPlatformEnabledCache = MockPlatform();
mockPlatformEnabledCache.environment['DISABLE_FLUTTER_BUILD_CACHE'] = 'false'; mockPlatformEnabledCache.environment['DISABLE_FLUTTER_BUILD_CACHE'] = 'false';
...@@ -231,7 +232,8 @@ void main() { ...@@ -231,7 +232,8 @@ void main() {
expect(await fingerprinter.doesFingerprintMatch(), isTrue); expect(await fingerprinter.doesFingerprintMatch(), isTrue);
}, overrides: <Type, Generator>{ }, overrides: <Type, Generator>{
Platform: () => mockPlatformEnabledCache, Platform: () => mockPlatformEnabledCache,
}..addAll(contextOverrides)); ...contextOverrides,
});
testUsingContext('fails to write fingerprint if inputs are missing', () async { testUsingContext('fails to write fingerprint if inputs are missing', () async {
final Fingerprinter fingerprinter = Fingerprinter( final Fingerprinter fingerprinter = Fingerprinter(
......
...@@ -53,13 +53,11 @@ void main() { ...@@ -53,13 +53,11 @@ void main() {
Future<BuildBundleCommand> runCommandIn(String projectPath, { List<String> arguments }) async { Future<BuildBundleCommand> runCommandIn(String projectPath, { List<String> arguments }) async {
final BuildBundleCommand command = BuildBundleCommand(bundleBuilder: mockBundleBuilder); final BuildBundleCommand command = BuildBundleCommand(bundleBuilder: mockBundleBuilder);
final CommandRunner<void> runner = createTestCommandRunner(command); final CommandRunner<void> runner = createTestCommandRunner(command);
await runner.run(<String>[
final List<String> commandArgs = <String>['bundle']; 'bundle',
if (arguments != null) ...?arguments,
commandArgs.addAll(arguments); '--target=$projectPath/lib/main.dart',
commandArgs.add('--target=$projectPath/lib/main.dart'); ]);
await runner.run(commandArgs);
return command; return command;
} }
......
...@@ -1129,10 +1129,11 @@ Future<void> _createProject( ...@@ -1129,10 +1129,11 @@ Future<void> _createProject(
Cache.flutterRoot = '../..'; Cache.flutterRoot = '../..';
final CreateCommand command = CreateCommand(); final CreateCommand command = CreateCommand();
final CommandRunner<void> runner = createTestCommandRunner(command); final CommandRunner<void> runner = createTestCommandRunner(command);
final List<String> args = <String>['create']; await runner.run(<String>[
args.addAll(createArgs); 'create',
args.add(dir.path); ...createArgs,
await runner.run(args); dir.path,
]);
bool pathExists(String path) { bool pathExists(String path) {
final String fullPath = fs.path.join(dir.path, path); final String fullPath = fs.path.join(dir.path, path);
......
...@@ -85,9 +85,11 @@ void main() { ...@@ -85,9 +85,11 @@ void main() {
dir ??= tempDir; dir ??= tempDir;
final IdeConfigCommand command = IdeConfigCommand(); final IdeConfigCommand command = IdeConfigCommand();
final CommandRunner<void> runner = createTestCommandRunner(command); final CommandRunner<void> runner = createTestCommandRunner(command);
final List<String> finalArgs = <String>['--flutter-root=${tempDir.absolute.path}', 'ide-config']; await runner.run(<String>[
finalArgs.addAll(args); '--flutter-root=${tempDir.absolute.path}',
await runner.run(finalArgs); 'ide-config',
...args,
]);
for (String path in expectedContents.keys) { for (String path in expectedContents.keys) {
final String absPath = fs.path.join(tempDir.absolute.path, path); final String absPath = fs.path.join(tempDir.absolute.path, path);
...@@ -148,8 +150,10 @@ void main() { ...@@ -148,8 +150,10 @@ void main() {
'template', 'template',
); );
_populateDir(templateManifest); _populateDir(templateManifest);
final Map<String, String> expectedContents = templateManifest; final Map<String, String> expectedContents = <String, String>{
expectedContents.addAll(flutterManifest); ...templateManifest,
...flutterManifest,
};
return _updateIdeConfig( return _updateIdeConfig(
expectedContents: expectedContents, expectedContents: expectedContents,
); );
...@@ -171,8 +175,10 @@ void main() { ...@@ -171,8 +175,10 @@ void main() {
tempDir, tempDir,
'template', 'template',
); );
final Map<String, String> expectedContents = templateManifest; final Map<String, String> expectedContents = <String, String>{
expectedContents.addAll(overwrittenManifest); ...templateManifest,
...overwrittenManifest,
};
return _updateIdeConfig( return _updateIdeConfig(
args: <String>['--overwrite'], args: <String>['--overwrite'],
expectedContents: expectedContents, expectedContents: expectedContents,
...@@ -200,8 +206,10 @@ void main() { ...@@ -200,8 +206,10 @@ void main() {
'existing', 'existing',
); );
_populateDir(flutterManifest); _populateDir(flutterManifest);
final Map<String, String> expectedContents = flutterManifest; final Map<String, String> expectedContents = <String, String>{
expectedContents.addAll(templateManifest); ...flutterManifest,
...templateManifest,
};
return _updateIdeConfig( return _updateIdeConfig(
args: <String>['--update-templates'], args: <String>['--update-templates'],
expectedContents: expectedContents, expectedContents: expectedContents,
...@@ -225,8 +233,10 @@ void main() { ...@@ -225,8 +233,10 @@ void main() {
'existing', 'existing',
isTemplate: true, isTemplate: true,
); );
final Map<String, String> expectedContents = flutterManifest; final Map<String, String> expectedContents = <String, String>{
expectedContents.addAll(updatedTemplates); ...flutterManifest,
...updatedTemplates,
};
return _updateIdeConfig( return _updateIdeConfig(
args: <String>['--update-templates', '--overwrite'], args: <String>['--update-templates', '--overwrite'],
expectedContents: expectedContents, expectedContents: expectedContents,
...@@ -259,8 +269,10 @@ void main() { ...@@ -259,8 +269,10 @@ void main() {
'flutter.iml${Template.copyTemplateExtension}', 'flutter.iml${Template.copyTemplateExtension}',
); );
updatedTemplates.remove(flutterIml); updatedTemplates.remove(flutterIml);
final Map<String, String> expectedContents = flutterManifest; final Map<String, String> expectedContents = <String, String>{
expectedContents.addAll(updatedTemplates); ...flutterManifest,
...updatedTemplates,
};
return _updateIdeConfig( return _updateIdeConfig(
args: <String>['--update-templates', '--overwrite'], args: <String>['--update-templates', '--overwrite'],
expectedContents: expectedContents, expectedContents: expectedContents,
...@@ -298,8 +310,10 @@ void main() { ...@@ -298,8 +310,10 @@ void main() {
updatedTemplates.remove(deepIml); updatedTemplates.remove(deepIml);
deepIml = fs.path.join(deepIml, 'deep.iml'); deepIml = fs.path.join(deepIml, 'deep.iml');
updatedTemplates.remove(deepIml); updatedTemplates.remove(deepIml);
final Map<String, String> expectedContents = flutterManifest; final Map<String, String> expectedContents = <String, String>{
expectedContents.addAll(updatedTemplates); ...flutterManifest,
...updatedTemplates,
};
return _updateIdeConfig( return _updateIdeConfig(
args: <String>['--update-templates', '--overwrite'], args: <String>['--update-templates', '--overwrite'],
expectedContents: expectedContents, expectedContents: expectedContents,
......
...@@ -61,13 +61,12 @@ void main() { ...@@ -61,13 +61,12 @@ void main() {
Future<PackagesCommand> runCommandIn(String projectPath, String verb, { List<String> args }) async { Future<PackagesCommand> runCommandIn(String projectPath, String verb, { List<String> args }) async {
final PackagesCommand command = PackagesCommand(); final PackagesCommand command = PackagesCommand();
final CommandRunner<void> runner = createTestCommandRunner(command); final CommandRunner<void> runner = createTestCommandRunner(command);
await runner.run(<String>[
final List<String> commandArgs = <String>['packages', verb]; 'packages',
if (args != null) verb,
commandArgs.addAll(args); ...?args,
commandArgs.add(projectPath); projectPath,
]);
await runner.run(commandArgs);
return command; return command;
} }
......
...@@ -77,15 +77,13 @@ class Testbed { ...@@ -77,15 +77,13 @@ class Testbed {
/// `overrides` may be used to provide new context values for the single test /// `overrides` may be used to provide new context values for the single test
/// case or override any context values from the setup. /// case or override any context values from the setup.
FutureOr<T> run<T>(FutureOr<T> Function() test, {Map<Type, Generator> overrides}) { FutureOr<T> run<T>(FutureOr<T> Function() test, {Map<Type, Generator> overrides}) {
final Map<Type, Generator> testOverrides = Map<Type, Generator>.from(_testbedDefaults); final Map<Type, Generator> testOverrides = <Type, Generator>{
// Add the initial setUp overrides ..._testbedDefaults,
if (_overrides != null) { // Add the initial setUp overrides
testOverrides.addAll(_overrides); ...?_overrides,
} // Add the test-specific overrides
// Add the test-specific overrides ...?overrides,
if (overrides != null) { };
testOverrides.addAll(overrides);
}
// Cache the original flutter root to restore after the test case. // Cache the original flutter root to restore after the test case.
final String originalFlutterRoot = Cache.flutterRoot; final String originalFlutterRoot = Cache.flutterRoot;
return runInContext<T>(() { return runInContext<T>(() {
......
...@@ -606,24 +606,21 @@ class _SshPortForwarder implements PortForwarder { ...@@ -606,24 +606,21 @@ class _SshPortForwarder implements PortForwarder {
// IPv6 interface, it cannot be used to connect to a websocket. // IPv6 interface, it cannot be used to connect to a websocket.
final String formattedForwardingUrl = final String formattedForwardingUrl =
'${localSocket.port}:$_ipv4Loopback:$remotePort'; '${localSocket.port}:$_ipv4Loopback:$remotePort';
final List<String> command = <String>['ssh'];
if (isIpV6) {
command.add('-6');
}
if (sshConfigPath != null) {
command.addAll(<String>['-F', sshConfigPath]);
}
final String targetAddress = final String targetAddress =
isIpV6 && interface.isNotEmpty ? '$address%$interface' : address; isIpV6 && interface.isNotEmpty ? '$address%$interface' : address;
const String dummyRemoteCommand = 'true'; const String dummyRemoteCommand = 'true';
command.addAll(<String>[ final List<String> command = <String>[
'ssh',
if (isIpV6) '-6',
if (sshConfigPath != null)
...<String>['-F', sshConfigPath],
'-nNT', '-nNT',
'-f', '-f',
'-L', '-L',
formattedForwardingUrl, formattedForwardingUrl,
targetAddress, targetAddress,
dummyRemoteCommand, dummyRemoteCommand,
]); ];
_log.fine("_SshPortForwarder running '${command.join(' ')}'"); _log.fine("_SshPortForwarder running '${command.join(' ')}'");
// Must await for the port forwarding function to completer here, as // Must await for the port forwarding function to completer here, as
// forwarding must be completed before surfacing VM events (as the user may // forwarding must be completed before surfacing VM events (as the user may
...@@ -649,20 +646,19 @@ class _SshPortForwarder implements PortForwarder { ...@@ -649,20 +646,19 @@ class _SshPortForwarder implements PortForwarder {
// uses the IPv4 loopback. // uses the IPv4 loopback.
final String formattedForwardingUrl = final String formattedForwardingUrl =
'${_localSocket.port}:$_ipv4Loopback:$_remotePort'; '${_localSocket.port}:$_ipv4Loopback:$_remotePort';
final List<String> command = <String>['ssh'];
final String targetAddress = _ipV6 && _interface.isNotEmpty final String targetAddress = _ipV6 && _interface.isNotEmpty
? '$_remoteAddress%$_interface' ? '$_remoteAddress%$_interface'
: _remoteAddress; : _remoteAddress;
if (_sshConfigPath != null) { final List<String> command = <String>[
command.addAll(<String>['-F', _sshConfigPath]); 'ssh',
} if (_sshConfigPath != null)
command.addAll(<String>[ ...<String>['-F', _sshConfigPath],
'-O', '-O',
'cancel', 'cancel',
'-L', '-L',
formattedForwardingUrl, formattedForwardingUrl,
targetAddress, targetAddress,
]); ];
_log.fine( _log.fine(
'Shutting down SSH forwarding with command: ${command.join(' ')}'); 'Shutting down SSH forwarding with command: ${command.join(' ')}');
final ProcessResult result = await _processManager.run(command); final ProcessResult result = await _processManager.run(command);
......
...@@ -82,18 +82,16 @@ class SshCommandRunner { ...@@ -82,18 +82,16 @@ class SshCommandRunner {
/// If the subprocess creating the SSH tunnel returns a nonzero exit status, /// If the subprocess creating the SSH tunnel returns a nonzero exit status,
/// then an [SshCommandError] is raised. /// then an [SshCommandError] is raised.
Future<List<String>> run(String command) async { Future<List<String>> run(String command) async {
final List<String> args = <String>['ssh']; final List<String> args = <String>[
if (sshConfigPath != null) { 'ssh',
args.addAll(<String>['-F', sshConfigPath]); if (sshConfigPath != null)
} ...<String>['-F', sshConfigPath],
if (isIpV6Address(address)) { if (isIpV6Address(address))
final String fullAddress = ...<String>['-6', interface.isEmpty ? address : '$address%$interface']
interface.isEmpty ? address : '$address%$interface'; else
args.addAll(<String>['-6', fullAddress]); address,
} else { command,
args.add(address); ];
}
args.add(command);
_log.fine('Running command through SSH: ${args.join(' ')}'); _log.fine('Running command through SSH: ${args.join(' ')}');
final ProcessResult result = await _processManager.run(args); final ProcessResult result = await _processManager.run(args);
if (result.exitCode != 0) { if (result.exitCode != 0) {
......
...@@ -5,7 +5,7 @@ author: Flutter Authors <flutter-dev@googlegroups.com> ...@@ -5,7 +5,7 @@ author: Flutter Authors <flutter-dev@googlegroups.com>
environment: environment:
# The pub client defaults to an <2.0.0 sdk constraint which we need to explicitly overwrite. # The pub client defaults to an <2.0.0 sdk constraint which we need to explicitly overwrite.
sdk: ">=2.2.0 <3.0.0" sdk: ">=2.2.2 <3.0.0"
dependencies: dependencies:
json_rpc_2: 2.1.0 json_rpc_2: 2.1.0
......
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