Skip to content

Commit

Permalink
[tools/] remove many uses of dynamic in the tools/ directory
Browse files Browse the repository at this point in the history
Change-Id: I1bd930c11e0463ba0de1938ba417b6664c8cdb28
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/376023
Reviewed-by: Nate Bosch <nbosch@google.com>
Commit-Queue: Devon Carew <devoncarew@google.com>
Reviewed-by: Alexander Thomas <athom@google.com>
  • Loading branch information
devoncarew authored and Commit Queue committed Jul 17, 2024
1 parent db35cbf commit dd5b9cd
Show file tree
Hide file tree
Showing 11 changed files with 73 additions and 60 deletions.
5 changes: 3 additions & 2 deletions tools/analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ analyzer:
- dart2js/**
- dom/**
- test_generators/**
language:
strict-inference: true

linter:
rules:
# TODO: Enable this once other issues are addressed.
# - avoid_dynamic_calls
- avoid_dynamic_calls
- comment_references
- depend_on_referenced_packages
- directives_ordering
Expand Down
6 changes: 3 additions & 3 deletions tools/bots/find_base_commit.dart
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,14 @@ ${parser.usage}""");
// can, the first time we see a commit, we know it's newer than all commits
// we haven't seen yet. The insertion order into the buildersForCommits map
// will then sorted with the newest commit first.
final builds = searchResult["builds"];
final builds = searchResult["builds"] as List<Map>?;
if (builds == null) {
print("No builds found");
exit(1);
}
final buildersForCommits = <String, Set<String>>{};
for (final build in builds) {
final builder = build["builder"]?["builder"];
final builder = (build["builder"] as Map?)?["builder"];
if (builder is! String ||
builder.endsWith("-beta") ||
builder.endsWith("-dev") ||
Expand All @@ -120,7 +120,7 @@ ${parser.usage}""");
// Filter way builders we're not interested in.
continue;
}
final input = build["input"]?["gitilesCommit"];
final input = (build["input"] as Map?)?["gitilesCommit"] as Map?;
if (input == null) {
// Ignore builds not triggered by a commit, e.g. fuzz-linux.
continue;
Expand Down
41 changes: 21 additions & 20 deletions tools/bots/get_builder_status.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ String get buildTable => builder.endsWith('-try') ? 'try_builds' : 'builds';
String get resultsTable => builder.endsWith('-try') ? 'try_results' : 'results';

bool booleanFieldOrFalse(Map<String, dynamic> document, String field) {
final fieldObject = document['fields'][field];
return fieldObject?['booleanValue'] ?? false;
final fieldObject = (document['fields'] as Map)[field];
return (fieldObject as Map?)?['booleanValue'] ?? false;
}

void usage(ArgParser parser) {
Expand Down Expand Up @@ -100,8 +100,8 @@ void main(List<String> args) async {
'when fetching build data');
exit(2);
}
final documents = jsonDecode(response.body);
final document = documents.first['document'];
final documents = jsonDecode(response.body) as List;
final document = (documents.first as Map)['document'];
if (document == null) {
print('No results received for build $buildNumber of $builder');
exit(2);
Expand Down Expand Up @@ -133,7 +133,7 @@ Future<List<String>> getConfigurations() async {
final groups = <String>{
for (Map document in documents)
if (document.containsKey('document'))
document['document']['name'].split('/').last
((document['document'] as Map)['name'] as String).split('/').last
};
return groups.toList();
}
Expand All @@ -145,9 +145,10 @@ Future<String> commitHash(int index) =>
Future<String> fetchCommitHash(int index) async {
final response = await runFirestoreQuery(commitQuery(index));
if (response.statusCode == HttpStatus.ok) {
final document = jsonDecode(response.body).first['document'];
final documents = jsonDecode(response.body) as List;
final document = (documents.first as Map)['document'] as Map?;
if (document != null) {
return document['name'].split('/').last;
return (document['name'] as String).split('/').last;
}
}
print('Could not fetch commit with index $index');
Expand All @@ -161,20 +162,20 @@ Future<Map<String, List<Map<String, dynamic>>>> fetchActiveFailures(
final response =
await runFirestoreQuery(unapprovedFailuresQuery(configuration));
if (response.statusCode == HttpStatus.ok) {
final documents = jsonDecode(response.body);
final documents = (jsonDecode(response.body) as List).cast<Map>();
for (final documentItem in documents) {
final document = documentItem['document'];
final document = documentItem['document'] as Map?;
if (document == null) continue;
final fields = document['fields'];
final fields = document['fields'] as Map;
failures.putIfAbsent(configuration, () => []).add({
'name': fields['name']['stringValue'],
'start_commit': await commitHash(
int.parse(fields['blamelist_start_index']['integerValue'])),
'end_commit': await commitHash(
int.parse(fields['blamelist_end_index']['integerValue'])),
'result': fields['result']['stringValue'],
'expected': fields['expected']['stringValue'],
'previous': fields['previous_result']['stringValue'],
'name': (fields['name'] as Map)['stringValue'],
'start_commit': await commitHash(int.parse(
(fields['blamelist_start_index'] as Map)['integerValue'])),
'end_commit': await commitHash(int.parse(
(fields['blamelist_end_index'] as Map)['integerValue'])),
'result': (fields['result'] as Map)['stringValue'],
'expected': (fields['expected'] as Map)['stringValue'],
'previous': (fields['previous_result'] as Map)['stringValue'],
});
}
}
Expand All @@ -196,10 +197,10 @@ void printActiveFailures(Map<String, List<Map<String, dynamic>>> failures) {
', expected ',
failure['expected'],
') at ',
failure['start_commit'].substring(0, 6),
(failure['start_commit'] as String).substring(0, 6),
if (failure['end_commit'] != failure['start_commit']) ...[
'..',
failure['end_commit'].substring(0, 6)
(failure['end_commit'] as String).substring(0, 6)
]
].join(''));
}
Expand Down
2 changes: 1 addition & 1 deletion tools/bots/lib/src/firestore.dart
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ class FirestoreDatabase {
var response =
await _client.post(_beginTransactionUrl, headers: _headers, body: body);
if (response.statusCode == HttpStatus.ok) {
var result = jsonDecode(response.body);
var result = jsonDecode(response.body) as Map<String, dynamic>;
_currentTransaction = result['transaction'] as String;
if (_currentTransaction == null) {
throw Exception("Call returned no transaction identifier");
Expand Down
20 changes: 11 additions & 9 deletions tools/bots/update_blamelists.dart
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ const maxAttempts = 20;
late FirestoreDatabase database;

class ResultRecord {
final Map data;
final Map<String, dynamic> data;

ResultRecord(this.data);

Map field(String name) => data['fields'][name] /*!*/;
Map field(String name) => (data['fields'] as Map)[name];

int get blamelistStartIndex {
return int.parse(field('blamelist_start_index')['integerValue']);
Expand Down Expand Up @@ -61,8 +61,9 @@ Query unapprovedActiveFailuresQuery(String configuration) {

Future<int> getCommitIndex(String commit) async {
try {
Map document = await database.getDocument('commits', commit);
var index = document['fields']['index'];
var document =
(await database.getDocument('commits', commit)).cast<String, dynamic>();
var index = (document['fields'] as Map)['index'] as Map;
if (index['integerValue'] == null) {
throw Exception('Expected an integer, but got "$index"');
}
Expand Down Expand Up @@ -103,14 +104,15 @@ Future<void> updateBlameLists(String configuration, String commit,
int attempts = 0;
do {
needsRetry = false;
var documents = (await database.runQuery(query))
var documentPaths = (await database.runQuery(query))
.cast<Map>()
.where((result) => result['document'] != null)
.map((result) => result['document']['name']);
for (var documentPath in documents) {
.map((result) => (result['document'] as Map)['name'] as String);
for (var documentPath in documentPaths) {
database.beginTransaction();
var documentName = documentPath.split('/').last;
var result =
ResultRecord(await database.getDocument('results', documentName));
final docMap = await database.getDocument('results', documentName);
var result = ResultRecord(docMap.cast<String, dynamic>());
if (commitIndex < result.blamelistStartIndex ||
commitIndex >= result.blamelistEndIndex) {
continue;
Expand Down
13 changes: 7 additions & 6 deletions tools/bots/update_flakiness.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,16 @@ ${parser.usage}''');
testData['last_new_result_seen'] = nowString;
}
if (testData['current'] == result) {
testData['current_counter']++;
var currentCounter = testData['current_counter'] as int;
testData['current_counter'] = currentCounter + 1;
} else {
testData['current'] = result;
testData['current_counter'] = 1;
}
Map<String, dynamic> mapField(String key) =>
testData[key] ??= <String, dynamic>{};
mapField('occurrences')[result] =
(mapField('occurrences')[result] ?? 0) + 1;
(mapField('occurrences')[result] as int? ?? 0) + 1;
mapField('first_seen')[result] ??= nowString;
mapField('last_seen')[result] = nowString;
mapField('matches')[result] = resultObject['matches'];
Expand All @@ -96,23 +97,23 @@ ${parser.usage}''');
final keys = data.keys.toList()..sort();
for (final key in keys) {
final testData = data[key]!;
if (testData['outcomes'].length < 2) continue;
if ((testData['outcomes'] as List).length < 2) continue;
// Reactivate inactive flaky results that are flaky again.
if (testData['active'] == false) {
if (resultsForInactiveFlakiness[key]!.length > 1) {
testData['active'] = true;
testData['reactivation_count'] =
(testData['reactivation_count'] ?? 0) + 1;
(testData['reactivation_count'] as int? ?? 0) + 1;
}
} else if (options.flag('no-forgive')) {
testData['active'] = true;
} else if (testData['current_counter'] >= 100) {
} else if (testData['current_counter'] as int >= 100) {
// Forgive tests that have been stable for 100 builds.
testData['active'] = false;
} else {
// Forgive tests that have been stable since flakiness horizon (one week).
final resultTimes = [
for (final timeString in testData['last_seen'].values)
for (final timeString in (testData['last_seen'] as Map).values)
DateTime.parse(timeString)
]..sort();
// The latest timestamp is the current result. The one before that is the
Expand Down
17 changes: 10 additions & 7 deletions tools/diff_results.dart
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ Future<DateTime> getDateOfCommit(String commit) async {
print(result.stderr);
exit(1);
}
return DateTime.parse(result.stdout.trim());
return DateTime.parse((result.stdout as String).trim());
}

Future<List<Result>> getResults(
Expand Down Expand Up @@ -147,12 +147,12 @@ Future<List<Result>> getResults(
} else {
print('Running the following query failed:\nbq ${arguments.join(' ')}');
print('Exit code: ${result.exitCode}');
final stdout = result.stdout.trim();
if (stdout.length > 0) {
final stdout = (result.stdout as String).trim();
if (stdout.isNotEmpty) {
print('Stdout:\n$stdout');
}
final stderr = result.stderr.trim();
if (stderr.length > 0) {
final stderr = (result.stderr as String).trim();
if (stderr.isNotEmpty) {
print('Stderr:\n$stderr');
}
return <Result>[];
Expand Down Expand Up @@ -327,11 +327,14 @@ String currentDate() {

Set<String> loadVmBuildersFromTestMatrix(List<Glob> globs) {
final contents = File('tools/bots/test_matrix.json').readAsStringSync();
final testMatrix = json.decode(contents);
final testMatrix = json.decode(contents) as Map<String, dynamic>;

final vmBuilders = <String>{};
for (final config in testMatrix['builder_configurations']) {
for (final builder in config['builders']) {
for (final builder in (config as Map)['builders']) {
// Cast to a string.
builder as String;

if (builder.startsWith('vm-') || builder.startsWith('app-')) {
vmBuilders.add(builder);
}
Expand Down
11 changes: 7 additions & 4 deletions tools/find_builders.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,11 @@ Future<List<String>> _testGetConfigurations(String testName) async {
queryParameters: {'filter': testName},
);
final response = await _get(requestUrl);
final object = jsonDecode(response);
return [for (final result in object['results']) result['configuration']];
final object = jsonDecode(response) as Map<String, dynamic>;
return [
for (final result in ((object['results'] as List)).cast<Map>())
result['configuration']
];
}

Future<String> _get(Uri requestUrl) async {
Expand Down Expand Up @@ -100,9 +103,9 @@ Stream<Map<String, dynamic>> _configurationDocuments() async* {
},
);
final response = await _get(requestUrl);
final object = jsonDecode(response);
final object = jsonDecode(response) as Map<String, dynamic>;
yield* Stream.fromIterable(
object['documents'].cast<Map<String, dynamic>>());
(object['documents'] as List).cast<Map<String, dynamic>>());

nextPageToken = object['nextPageToken'];
} while (nextPageToken != null);
Expand Down
7 changes: 4 additions & 3 deletions tools/generate_experimental_flags.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,13 @@ void main() {

YamlMap features = yaml['features'];
for (var entry in features.entries) {
final category = (entry.value as YamlMap)['category'];
final value = entry.value as YamlMap;
final category = value['category'];
if (category == null || category == "vm" || category == "language") {
final version = getAsVersionNumber((entry.value as YamlMap)['enabledIn']);
final version = getAsVersionNumber(value['enabledIn']);
if (version != null) {
final value = isGreaterOrEqualVersion(currentVersion, version);
final name = entry.key.replaceAll('-', '_');
final name = (entry.key as String).replaceAll('-', '_');
enumNames.write(' $name,\n');
featureValues.write(' $value,\n');
featureNames.write(' "${entry.key}",\n');
Expand Down
9 changes: 5 additions & 4 deletions tools/package_deps/bin/package_deps.dart
Original file line number Diff line number Diff line change
Expand Up @@ -100,15 +100,16 @@ class Package implements Comparable<Package> {
Package(this.dir) {
var pubspec = File(path.join(dir, 'pubspec.yaml'));
var doc = yaml.loadYamlDocument(pubspec.readAsStringSync());
dynamic contents = doc.contents.value;
var contents = doc.contents as yaml.YamlMap;
_packageName = contents['name'];
_publishToNone = contents['publish_to'] == 'none';

Set<String> process(String section, List<PubDep> target) {
if (contents[section] != null) {
final value = Set<String>.from(contents[section].keys);
final value =
Set<String>.from((contents[section] as yaml.YamlMap).keys);

var deps = contents[section];
var deps = contents[section] as yaml.YamlMap;
for (var package in deps.keys) {
target.add(PubDep.parse(package, deps[package]));
}
Expand Down Expand Up @@ -469,7 +470,7 @@ class SdkDeps {
var pubspec = File(path.join(dir.path, 'pubspec.yaml'));
if (pubspec.existsSync()) {
var doc = yaml.loadYamlDocument(pubspec.readAsStringSync());
dynamic contents = doc.contents.value;
var contents = doc.contents as yaml.YamlMap;
var name = contents['name'];
var version = contents['version'];
var dep = ResolvedDep(
Expand Down
2 changes: 1 addition & 1 deletion tools/spec_parser/spec_parse.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const String javaExecutable = 'java';
void main(List<String> arguments) {
for (String arg in arguments) {
void handleResult(ProcessResult result) {
if (result.stderr.length != 0) {
if ((result.stderr as String).isNotEmpty) {
print('Error parsing $arg:\n${result.stderr}');
}
print(result.stdout);
Expand Down

0 comments on commit dd5b9cd

Please sign in to comment.