Skip to content

Commit

Permalink
Fix analyzer errors (exercism#271)
Browse files Browse the repository at this point in the history
- Move constructor to top of class order (acba2b3)
- create_exercise: Replace use of dynamic with a specific cast (823bb24)
- Apply final to local variables to allow the compiler to do optimizations (f50367e)
  • Loading branch information
Stargator authored Dec 4, 2020
1 parent bc5cabe commit 475e5e2
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 45 deletions.
42 changes: 22 additions & 20 deletions bin/create_exercise.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ List<String> words(String str) {

/// Converts first character to upper case.
String upperFirst(String str) {
if (str == null || str.length == 0) return '';
if (str == null || str.isEmpty) return '';

final chars = str.split('');
final first = chars.first;
Expand Down Expand Up @@ -130,15 +130,17 @@ String testCaseTemplate(String exerciseName, Map<String, Object> testCase, {bool
}

// We have a group, not a case
String description = _handleQuotes(testCase['description'] as String);
final description = _handleQuotes(testCase['description'] as String);

// Build the tests up recursively, only first test should be skipped
List<String> testList = <String>[];
for (Map<String, Object> caseObj in testCase['cases'] as dynamic) {
final testList = <String>[];

for (Map<String, Object> caseObj in testCase['cases'] as List<Map<String, Object>>) {
testList.add(testCaseTemplate(exerciseName, caseObj, firstTest: skipTests, returnType: returnType));
skipTests = false;
}
String tests = testList.join('\n');

final tests = testList.join('\n');

if (description == null) {
return tests;
Expand All @@ -151,13 +153,13 @@ String testCaseTemplate(String exerciseName, Map<String, Object> testCase, {bool
''';
}

String description = _repr(testCase['description']);
String object = camelCase(exerciseName);
String method = testCase['property'].toString();
String expected = _repr(testCase['expected'], typeDeclaration: returnType);
final description = _repr(testCase['description']);
final object = camelCase(exerciseName);
final method = testCase['property'].toString();
final expected = _repr(testCase['expected'], typeDeclaration: returnType);

returnType = _finalizeReturnType(expected, returnType);
Map<String, dynamic> input = testCase['input'] as Map<String, dynamic>;
final input = testCase['input'] as Map<String, dynamic>;
String arguments = input.keys.map((k) => _repr(input[k])).join(', ');
arguments = arguments == 'null' ? '' : arguments;

Expand Down Expand Up @@ -203,7 +205,7 @@ String _finalizeReturnType(String expected, String returnType) {
bool _doGenerate(Directory exerciseDir, String exerciseName, String version) {
if (exerciseDir.existsSync()) {
if (File('${exerciseDir.path}/pubspec.yaml').existsSync()) {
String pubspecString = File('${exerciseDir.path}/pubspec.yaml').readAsStringSync();
final pubspecString = File('${exerciseDir.path}/pubspec.yaml').readAsStringSync();
final currentVersion = loadYaml(pubspecString)['version'] as String;

if (currentVersion == version) {
Expand All @@ -230,7 +232,7 @@ void _generateExercise(Map<String, Object> specification, String exerciseFilenam
Directory('${exerciseDir.path}/test').createSync(recursive: true);

// Create files
String testFileName = '${exerciseDir.path}/test/${exerciseFilename}_test.dart';
final testFileName = '${exerciseDir.path}/test/${exerciseFilename}_test.dart';
File('${exerciseDir.path}/lib/example.dart').writeAsStringSync(exampleTemplate(exerciseName));
File('${exerciseDir.path}/lib/${exerciseFilename}.dart').writeAsStringSync(mainTemplate(exerciseName));
File(testFileName).writeAsStringSync(testTemplate(exerciseName));
Expand Down Expand Up @@ -267,7 +269,7 @@ void _generateExercise(Map<String, Object> specification, String exerciseFilenam

/// If a string contains a single backslash, we need to add another behind it, so the backslash remains.
String _escapeBackslash(String input) {
List<String> result = <String>[];
final result = <String>[];

input.split('').forEach((String value) {
if (value == r'\') {
Expand Down Expand Up @@ -335,7 +337,7 @@ Set<dynamic> retrieveListOfExpected(List<dynamic> testCases, {Set<dynamic> expec

for (var count = 0; count < testCases.length; count++) {
if (testCases[count] is Map) {
Map entry = testCases[count] as Map;
final entry = testCases[count] as Map;
bool addEntry = true;

if (entry.containsKey('expected')) {
Expand Down Expand Up @@ -430,7 +432,7 @@ String _defineMap(Map x, String iterableType) {

/// A helper method to get the inside type of an iterable
String _getIterableType(Iterable iter) {
Set<String> types = iter.map(_getFriendlyType).toSet();
final types = iter.map(_getFriendlyType).toSet();

if (types.length == 1) {
return types.first;
Expand All @@ -441,11 +443,11 @@ String _getIterableType(Iterable iter) {

/// A helper method to get the inside type of a map
String _getMapType(Map map) {
Set<String> keyTypes = map.keys.map(_getFriendlyType).toSet();
Set<String> valueTypes = map.values.map(_getFriendlyType).toSet();
final keyTypes = map.keys.map(_getFriendlyType).toSet();
final valueTypes = map.values.map(_getFriendlyType).toSet();

String mapKeyType = keyTypes.length == 1 ? keyTypes.first : 'dynamic';
String mapValueType = valueTypes.length == 1 ? valueTypes.first : 'dynamic';
final mapKeyType = keyTypes.length == 1 ? keyTypes.first : 'dynamic';
final mapValueType = valueTypes.length == 1 ? valueTypes.first : 'dynamic';

return '<$mapKeyType, $mapValueType>';
}
Expand Down Expand Up @@ -510,7 +512,7 @@ void main(List<String> args) {

// Get test cases from canonical-data.json, format tests
if (arguments['spec-path'] != null) {
String canonicalFilePath = '${arguments['spec-path']}/exercises/$exerciseName/canonical-data.json';
final canonicalFilePath = '${arguments['spec-path']}/exercises/$exerciseName/canonical-data.json';
try {
final canonicalDataJson = File(canonicalFilePath);
final source = canonicalDataJson.readAsStringSync();
Expand Down
8 changes: 4 additions & 4 deletions lib/src/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ import 'dart:io';
import 'package:io/io.dart';

class CommonUtils {
ProcessManager _manager;

CommonUtils() {
this._manager = ProcessManager();
}

ProcessManager _manager;

/// Fetches the configlet file if it doesn't exist already, and returns the
/// exit code.
int fetchConfiglet() {
File configletFile = File('bin/configlet');
final configletFile = File('bin/configlet');

if (!configletFile.existsSync()) {
print('Fetching configlet...');
Expand All @@ -25,7 +25,7 @@ class CommonUtils {
/// Returns a [Future] with the exit code resulting from running the
/// [executable] with [arguments].
Future<int> runCmd(String executable, [List<String> arguments = const []]) async {
Process spawn = await _manager.spawn(executable, arguments);
final spawn = await _manager.spawn(executable, arguments);
return _exit(await spawn.exitCode);
}

Expand Down
38 changes: 19 additions & 19 deletions test/create_exercise_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ linter:

group('testCaseTemplate tests', () {
test('simple test for a single case', () {
Map<String, dynamic> testCase = <String, dynamic>{
final testCase = <String, dynamic>{
'description': 'Zero is an Armstrong number',
'property': 'isArmstrongNumber',
'input': {'number': 0},
Expand All @@ -219,7 +219,7 @@ linter:

group('processing test cases', () {
test('single case', () {
List<Map<String, dynamic>> cases = <Map<String, dynamic>>[
final cases = <Map<String, dynamic>>[
<String, dynamic>{
'description': 'Say Hi!',
'property': 'hello',
Expand All @@ -228,14 +228,14 @@ linter:
}
];

Set<dynamic> actualSet = retrieveListOfExpected(cases);
Set<String> expectedSet = Set.of(['Hello, World!']);
final actualSet = retrieveListOfExpected(cases);
final expectedSet = Set.of(['Hello, World!']);

expect(actualSet, equals(expectedSet));
});

test('multiple cases', () {
List<Map<String, dynamic>> cases = <Map<String, dynamic>>[
final cases = <Map<String, dynamic>>[
<String, dynamic>{
'description': 'year not divisible by 4 in common year',
'property': 'leapYear',
Expand Down Expand Up @@ -274,14 +274,14 @@ linter:
}
];

Set<dynamic> actualSet = retrieveListOfExpected(cases);
Set<bool> expectedSet = Set.of([false, true]);
final actualSet = retrieveListOfExpected(cases);
final expectedSet = Set.of([false, true]);

expect(actualSet, equals(expectedSet));
});

test('nested case', () {
List<Map<String, dynamic>> cases = <Map<String, dynamic>>[
final cases = <Map<String, dynamic>>[
<String, dynamic>{
'description': 'Check if the given string is an isogram',
'comments': ['Output should be a boolean denoting if the string is a isogram or not.'],
Expand All @@ -296,14 +296,14 @@ linter:
}
];

Set<dynamic> actualSet = retrieveListOfExpected(cases);
Set<bool> expectedSet = Set.of([true]);
final actualSet = retrieveListOfExpected(cases);
final expectedSet = Set.of([true]);

expect(actualSet, equals(expectedSet));
});

test('three nested cases', () {
List<Map<String, dynamic>> cases = <Map<String, dynamic>>[
final cases = <Map<String, dynamic>>[
<String, dynamic>{
'description': 'Square the sum of the numbers up to the given number',
'cases': [
Expand Down Expand Up @@ -375,14 +375,14 @@ linter:
}
];

Set<dynamic> actualSet = retrieveListOfExpected(cases);
Set<int> expectedSet = Set.of([1, 225, 25502500, 55, 338350, 0, 170, 25164150]);
final actualSet = retrieveListOfExpected(cases);
final expectedSet = Set.of([1, 225, 25502500, 55, 338350, 0, 170, 25164150]);

expect(actualSet, equals(expectedSet));
});

test('uneven nested cases', () {
List<Map<String, dynamic>> cases = <Map<String, dynamic>>[
final cases = <Map<String, dynamic>>[
<String, dynamic>{
'description': 'data is retained',
'property': 'data',
Expand Down Expand Up @@ -434,8 +434,8 @@ linter:
}
];

Set<dynamic> actualSet = retrieveListOfExpected(cases);
Set<Map<String, dynamic>> expectedSet = Set.of([
final actualSet = retrieveListOfExpected(cases);
final expectedSet = Set.of([
<String, dynamic>{'data': '4', 'left': null, 'right': null},
<String, dynamic>{
'data': '4',
Expand All @@ -458,7 +458,7 @@ linter:
});

test('case with an expected error', () {
List<Map<String, dynamic>> cases = <Map<String, dynamic>>[
final cases = <Map<String, dynamic>>[
<String, dynamic>{
'description': 'zero is an error',
'property': 'steps',
Expand All @@ -467,8 +467,8 @@ linter:
}
];

Set<dynamic> actualSet = retrieveListOfExpected(cases);
Set<dynamic> expectedSet = Set<dynamic>();
final actualSet = retrieveListOfExpected(cases);
final expectedSet = Set<dynamic>();

expect(actualSet, equals(expectedSet));
});
Expand Down
4 changes: 2 additions & 2 deletions test/exercises_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ Future runTest(String path) async {

Directory.current = path;

String packageName = await getPackageName();
final packageName = await getPackageName();

print('''
================================================================================
Expand Down Expand Up @@ -99,7 +99,7 @@ Future runAllTests() async {

Directory.current = dartExercismRootDir.parent;

String packageName = await getPackageName();
final packageName = await getPackageName();

print('''
Expand Down

0 comments on commit 475e5e2

Please sign in to comment.