Skip to content

Commit 539840f

Browse files
srawlinsCommit Queue
authored andcommitted
dartdev: Simplify some JSON-parsing code; remove dead code
* In `_handleServerResponse`, use if-case with map patterns to avoid casts and null checks and repeatedly fetching map values. * Remove the castStringKeyedMap utility. After some other changes, most call-sites passed in a Map, so then half of the utility is not used. In the others, it seemed simplest to use `as Map` and `.cast()` inline. * Change some `dynamic` local variables to be `Object?` instead. * Replace `DartdevCommand.project` getter and `_project` field with a single final field. * Remove unused properties from `Project` and unused `PackageConfig` class. * Remove associated tests. Change-Id: I1f626ecc0e6e4d27ef24f65959fd4cb54fb5fc92 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/412980 Reviewed-by: Devon Carew <[email protected]> Commit-Queue: Samuel Rawlins <[email protected]>
1 parent c2a60ab commit 539840f

File tree

5 files changed

+22
-172
lines changed

5 files changed

+22
-172
lines changed

pkg/dartdev/lib/src/analysis_server.dart

Lines changed: 21 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,8 @@ class AnalysisServer {
6969
// {"event":"server.status","params":{"analysis":{"isAnalyzing":true}}}
7070
return _streamController('server.status')
7171
.stream
72-
.where((event) => event!['analysis'] != null)
73-
.map((event) => (event!['analysis']['isAnalyzing']!) as bool);
72+
.where((event) => event['analysis'] != null)
73+
.map((event) => (event['analysis']['isAnalyzing']!) as bool);
7474
}
7575

7676
/// This future completes when we next receive an analysis finished event
@@ -79,15 +79,15 @@ class AnalysisServer {
7979
Future<bool>? get analysisFinished => _analysisFinished?.future;
8080

8181
Stream<FileAnalysisErrors> get onErrors {
82-
// {"event":"analysis.errors","params":{"file":"/Users/.../lib/main.dart","errors":[]}}
82+
// {"event":"analysis.errors",
83+
// "params":{"file":"/Users/.../lib/main.dart","errors":[]}}
8384
return _streamController('analysis.errors').stream.map((event) {
84-
final file = event!['file'] as String;
85+
final file = event['file'] as String;
8586
final errorsList = event['errors'] as List<dynamic>;
86-
final errors = errorsList
87-
.map<Map<String, dynamic>>(castStringKeyedMap)
88-
.map<AnalysisError>(
89-
(Map<String, dynamic> json) => AnalysisError(json))
90-
.toList();
87+
final errors = [
88+
for (final error in errorsList)
89+
AnalysisError((error as Map).cast<String, dynamic>())
90+
];
9191
return FileAnalysisErrors(file, errors);
9292
});
9393
}
@@ -281,24 +281,18 @@ class AnalysisServer {
281281
void _handleServerResponse(String line) {
282282
log.trace('<== $line');
283283

284-
final dynamic response = json.decode(line);
284+
final response = json.decode(line) as Object?;
285285

286286
if (response is Map<String, dynamic>) {
287-
if (response['event'] != null) {
288-
final event = response['event'] as String;
289-
final dynamic params = response['params'];
290-
287+
if (response
288+
case {'event': final String event, 'params': final Object? params}) {
291289
if (params is Map<String, dynamic>) {
292-
_streamController(event).add(castStringKeyedMap(params));
290+
_streamController(event).add(params.cast<String, dynamic>());
293291
}
294-
} else if (response['id'] != null) {
295-
final id = response['id'];
296-
297-
if (response['error'] != null) {
298-
final error = castStringKeyedMap(response['error']);
299-
_requestCompleters
300-
.remove(id)
301-
?.completeError(RequestError.parse(error));
292+
} else if (response case {'id': final String id}) {
293+
if (response case {'error': final Map error}) {
294+
_requestCompleters.remove(id)?.completeError(
295+
RequestError.parse(error.cast<String, dynamic>()));
302296
} else {
303297
_requestCompleters.remove(id)?.complete(response['result'] ?? {});
304298
}
@@ -315,12 +309,13 @@ class AnalysisServer {
315309
'details:\n');
316310
// Fields are 'isFatal', 'message', and 'stackTrace'.
317311
log.stderr(err['message']);
318-
if (err['stackTrace'] != null) {
319-
log.stderr(err['stackTrace'] as String);
312+
final stackTrace = err['stackTrace'];
313+
if (stackTrace is String && stackTrace.isNotEmpty) {
314+
log.stderr(stackTrace);
320315
}
321316
}
322317

323-
StreamController<Map<String, dynamic>?> _streamController(String streamId) {
318+
StreamController<Map<String, dynamic>> _streamController(String streamId) {
324319
return _streamControllers.putIfAbsent(
325320
streamId, () => StreamController<Map<String, dynamic>>.broadcast());
326321
}

pkg/dartdev/lib/src/core.dart

Lines changed: 1 addition & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@ abstract class DartdevCommand extends Command<int> {
3232
final String _name;
3333
final String _description;
3434
final bool _verbose;
35-
36-
Project? _project;
35+
final Project project = Project();
3736

3837
@override
3938
final bool hidden;
@@ -70,8 +69,6 @@ abstract class DartdevCommand extends Command<int> {
7069
/// Subclasses can override this in order to create a customized ArgParser.
7170
ArgParser createArgParser() =>
7271
ArgParser(usageLineLength: dartdevUsageLineLength);
73-
74-
Project get project => _project ??= Project();
7572
}
7673

7774
extension DartDevCommand on Command {
@@ -147,8 +144,6 @@ Future _streamLineTransform(
147144
class Project {
148145
final Directory dir;
149146

150-
PackageConfig? _packageConfig;
151-
152147
Project() : dir = Directory.current;
153148

154149
Project.fromDirectory(this.dir);
@@ -157,37 +152,4 @@ class Project {
157152
FileSystemEntity.isFileSync(path.join(dir.path, 'pubspec.yaml'));
158153

159154
File get pubspecFile => File(path.join(dir.path, 'pubspec.yaml'));
160-
161-
bool get hasPackageConfigFile => packageConfig != null;
162-
163-
PackageConfig? get packageConfig {
164-
if (_packageConfig == null) {
165-
File file =
166-
File(path.join(dir.path, '.dart_tool', 'package_config.json'));
167-
168-
if (file.existsSync()) {
169-
try {
170-
dynamic contents = json.decode(file.readAsStringSync());
171-
_packageConfig = PackageConfig(contents);
172-
} catch (_) {}
173-
}
174-
}
175-
176-
return _packageConfig;
177-
}
178-
}
179-
180-
/// A simple representation of a `package_config.json` file.
181-
class PackageConfig {
182-
final Map<String, dynamic> contents;
183-
184-
PackageConfig(this.contents);
185-
186-
List<Map<String, dynamic>?> get packages {
187-
List<dynamic> packages = contents['packages'];
188-
return packages.map<Map<String, dynamic>?>(castStringKeyedMap).toList();
189-
}
190-
191-
bool hasDependency(String packageName) =>
192-
packages.any((element) => element!['name'] == packageName);
193155
}

pkg/dartdev/lib/src/utils.dart

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -109,13 +109,6 @@ ArgParser globalDartdevOptionsParser({bool verbose = false}) {
109109
return argParser;
110110
}
111111

112-
/// Given a data structure which is a Map of String to dynamic values, return
113-
/// the same structure (`Map<String, dynamic>`) with the correct runtime types.
114-
Map<String, dynamic> castStringKeyedMap(dynamic untyped) {
115-
final Map<dynamic, dynamic> map = untyped! as Map<dynamic, dynamic>;
116-
return map.cast<String, dynamic>();
117-
}
118-
119112
/// Emit the given word with the correct pluralization.
120113
String pluralize(String word, int count) => count == 1 ? word : '${word}s';
121114

pkg/dartdev/test/core_test.dart

Lines changed: 0 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
// for details. All rights reserved. Use of this source code is governed by a
33
// BSD-style license that can be found in the LICENSE file.
44

5-
import 'dart:convert';
65
import 'dart:io';
76

87
import 'package:dartdev/src/commands/analyze.dart';
@@ -20,7 +19,6 @@ import 'utils.dart';
2019
void main() {
2120
initGlobalState();
2221
group('DartdevCommand', _dartdevCommand);
23-
group('PackageConfig', _packageConfig);
2422
group('Project', _project);
2523
}
2624

@@ -110,19 +108,6 @@ void _dartdevCommand() {
110108
});
111109
}
112110

113-
void _packageConfig() {
114-
test('packages', () {
115-
PackageConfig packageConfig = PackageConfig(jsonDecode(_packageData));
116-
expect(packageConfig.packages, isNotEmpty);
117-
});
118-
119-
test('hasDependency', () {
120-
PackageConfig packageConfig = PackageConfig(jsonDecode(_packageData));
121-
expect(packageConfig.hasDependency('test'), isFalse);
122-
expect(packageConfig.hasDependency('lints'), isTrue);
123-
});
124-
}
125-
126111
void _project() {
127112
test('hasPubspecFile positive', () {
128113
final p = project();
@@ -138,43 +123,4 @@ void _project() {
138123
Project coreProj = Project.fromDirectory(p.dir);
139124
expect(coreProj.hasPubspecFile, isFalse);
140125
});
141-
142-
test('hasPackageConfigFile positive', () {
143-
final p = project();
144-
Project coreProj = Project.fromDirectory(p.dir);
145-
expect(coreProj.hasPackageConfigFile, isTrue);
146-
expect(coreProj.packageConfig, isNotNull);
147-
expect(coreProj.packageConfig!.packages, isNotEmpty);
148-
});
149-
150-
test('hasPackageConfigFile negative', () {
151-
final p = project();
152-
var packageConfig =
153-
File(path.join(p.dirPath, '.dart_tool/package_config.json'));
154-
packageConfig.deleteSync();
155-
Project coreProj = Project.fromDirectory(p.dir);
156-
expect(coreProj.hasPackageConfigFile, isFalse);
157-
});
158-
}
159-
160-
const String _packageData = '''{
161-
"configVersion": 2,
162-
"packages": [
163-
{
164-
"name": "lints",
165-
"rootUri": "file:///Users/.../.pub-cache/hosted/pub.dartlang.org/lints-1.0.1",
166-
"packageUri": "lib/",
167-
"languageVersion": "2.1"
168-
},
169-
{
170-
"name": "args",
171-
"rootUri": "../",
172-
"packageUri": "lib/",
173-
"languageVersion": "2.3"
174-
}
175-
],
176-
"generated": "2020-03-01T03:38:14.906205Z",
177-
"generator": "pub",
178-
"generatorVersion": "2.8.0-dev.10.0"
179126
}
180-
''';

pkg/dartdev/test/utils_test.dart

Lines changed: 0 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
// for details. All rights reserved. Use of this source code is governed by a
33
// BSD-style license that can be found in the LICENSE file.
44

5-
import 'dart:convert';
65
import 'dart:io';
76

87
import 'package:dartdev/src/utils.dart';
@@ -54,29 +53,6 @@ void main() {
5453
});
5554
});
5655

57-
group('castStringKeyedMap', () {
58-
test('fails', () {
59-
dynamic contents = json.decode(_packageData);
60-
List<dynamic> packages = contents['packages'];
61-
try {
62-
// ignore: unused_local_variable
63-
List<Map<String, dynamic>> mappedPackages =
64-
packages as List<Map<String, dynamic>>;
65-
fail('expected implicit cast to fail');
66-
} on TypeError {
67-
// TypeError is expected
68-
}
69-
});
70-
71-
test('succeeds', () {
72-
dynamic contents = json.decode(_packageData);
73-
List<dynamic> packages = contents['packages'];
74-
List<Map<String, dynamic>> mappedPackages =
75-
packages.map<Map<String, dynamic>>(castStringKeyedMap).toList();
76-
expect(mappedPackages, isList);
77-
});
78-
});
79-
8056
group('FileSystemEntityExtension', () {
8157
test('isDartFile', () {
8258
expect(File('foo.dart').isDartFile, isTrue);
@@ -185,25 +161,3 @@ void main() {
185161
});
186162
});
187163
}
188-
189-
const String _packageData = '''{
190-
"configVersion": 2,
191-
"packages": [
192-
{
193-
"name": "lints",
194-
"rootUri": "file:///Users/.../.pub-cache/hosted/pub.dartlang.org/lints-1.0.1",
195-
"packageUri": "lib/",
196-
"languageVersion": "2.1"
197-
},
198-
{
199-
"name": "args",
200-
"rootUri": "../",
201-
"packageUri": "lib/",
202-
"languageVersion": "2.3"
203-
}
204-
],
205-
"generated": "2020-03-01T03:38:14.906205Z",
206-
"generator": "pub",
207-
"generatorVersion": "2.8.0-dev.10.0"
208-
}
209-
''';

0 commit comments

Comments
 (0)