-
-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathcreate_exercise.dart
536 lines (435 loc) · 16.1 KB
/
create_exercise.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
import 'dart:convert';
import 'dart:io';
import 'package:args/args.dart';
import 'package:path/path.dart' show dirname;
import 'package:yaml/yaml.dart';
// Constants
const _scriptFileName = 'create-exercise';
const _defaultSet = <dynamic>{};
final _parser = ArgParser()
..addSeparator('Usage: $_scriptFileName [--spec-path path] <slug>')
..addOption('spec-path', help: 'The location of the problem-specifications directory.', valueHelp: 'path');
// Helpers
/// Determine the words within a string, so they can be placed in the proper case.
List<String> words(String? str) {
if (str == null) return [''];
return str.toLowerCase().replaceAll(RegExp(r'[^a-z0-9]'), ' ').replaceAll(RegExp(r' +'), ' ').trim().split(' ');
}
/// Converts first character to upper case.
String upperFirst(String? str) {
if (str == null || str.isEmpty) return '';
final chars = str.split('');
final first = chars.first;
return first.toUpperCase() + chars.skip(1).join('');
}
/// Converts given string to camelCase.
String camelCase(String str, {bool isUpperFirst = false}) {
final parts = words(str);
final first = parts.first;
final rest = parts.skip(1);
return (isUpperFirst ? upperFirst(first) : first) + rest.map(upperFirst).join('');
}
/// Converts given string to PascalCase.
String pascalCase(String str) => camelCase(str, isUpperFirst: true);
/// Converts given string to snake_case.
String snakeCase(String str) => words(str).join('_');
/// Converts given string to kebab-case.
String kebabCase(String str) => words(str).join('-');
// Templates
/// Generates the code for an example class.
String exampleTemplate(String name) => '''
class ${pascalCase(name)} {
}
''';
/// Generates the code for the starting file of an exercise.
String mainTemplate(String name) => '''
class ${pascalCase(name)} {
// Put your code here
}
''';
String _testCasesString = '''
test('should work', () {
// TODO
});''';
/// Sorts the import of packages, instantiates an instance of the exercise class, and defines the main
/// function's group of tests.
String testTemplate(String name) {
final packages = <String>[name, 'test'];
packages.sort();
return '''
import 'package:${snakeCase(packages[0])}/${snakeCase(packages[0])}.dart';
import 'package:${snakeCase(packages[1])}/${snakeCase(packages[1])}.dart';
final ${camelCase(name)} = ${pascalCase(name)}();
void main() {
group('${pascalCase(name)}', () {
$_testCasesString
});
}
''';
}
/// Generates the yaml code for a pubspec.yaml file.
String pubTemplate(String name, String version) => '''
name: '${snakeCase(name)}'
version: $version
environment:
sdk: '>=2.18.0 <3.0.0'
dev_dependencies:
test: '<2.0.0'
''';
/// Generates the yaml code for an analysis_options.yaml file
String analysisOptionsTemplate() => '''
analyzer:
strong-mode:
implicit-casts: false
implicit-dynamic: false
errors:
unused_element: error
unused_import: error
unused_local_variable: error
dead_code: error
linter:
rules:
# Error Rules
- avoid_relative_lib_imports
- avoid_types_as_parameter_names
- literal_only_boolean_expressions
- no_adjacent_strings_in_list
- valid_regexps
''';
/// Parses through the given test case (or group) in order to produce a String of code for the generated test suite.
String testCaseTemplate(String exerciseName, Map<String, dynamic> testCase,
{bool firstTest = true, String returnType = ''}) {
bool skipTests = firstTest;
if (testCase['cases'] != null) {
if (returnType.isEmpty) {
returnType = _determineBestReturnType(testCase['cases'] as List<dynamic>);
}
// We have a group, not a case
final description = _handleQuotes(testCase['description'] as String?);
// Build the tests up recursively, only first test should be skipped
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;
}
final tests = testList.join('\n');
if (description == null) {
return tests;
}
return '''
group('$description', () {
$tests
});
''';
}
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);
final input = testCase['input'] as Map<String, dynamic>;
String arguments = input.keys.map((k) => _repr(input[k])).join(', ');
arguments = arguments == 'null' ? '' : arguments;
if (_containsWhitespaceCodes(arguments)) {
arguments = _escapeWhitespace(arguments);
}
final result = '''
test($description, () {
final $returnType result = $object.$method($arguments);
expect(result, equals($expected));
}, skip: ${!skipTests});
''';
return result;
}
String _finalizeReturnType(String expected, String returnType) {
final expectedIterable = RegExp(r"(<[A-Za-z]+>\[[a-zA-Z0-9', *]{0,}\])");
final expectedMap = RegExp(r"(<[A-Za-z, ]+>\{[[a-zA-Z0-9':, ]{0,}\})");
if (expected.contains(expectedIterable)) {
final iterableType = RegExp(r'(<[A-Za-z]+>)');
final extracted = iterableType.stringMatch(expected);
return returnType.contains('List<List') ? returnType : 'List$extracted';
} else if (expected.contains(expectedMap)) {
final iterableType = RegExp(r'(<[A-Za-z, ]+>)');
final extracted = iterableType.stringMatch(expected);
return 'Map$extracted';
} else {
if (expected == 'false' || expected == 'true') {
return 'bool';
} else if (expected.contains(RegExp(r'([0-9.]+)')) || expected.contains(RegExp(r"('[a-zA-Z, \'!]{0,}')"))) {
return returnType;
} else {
return expected;
}
}
}
/// Determines whether the script should generate an exercise.
bool _doGenerate(Directory exerciseDir, String exerciseName, String version) {
if (exerciseDir.existsSync()) {
if (File('${exerciseDir.path}/pubspec.yaml').existsSync()) {
final pubspecString = File('${exerciseDir.path}/pubspec.yaml').readAsStringSync();
final currentVersion = loadYaml(pubspecString)['version'] as String?;
if (currentVersion == version) {
stderr.write('$exerciseName of version, $currentVersion, already exists\n');
exit(1);
} else {
return true;
}
}
stderr.write('$exerciseName already exists\n');
exit(1);
}
return true;
}
/// Creates/updates an exercise.
void _generateExercise(Map<String, Object> specification, String exerciseFilename, String exerciseName,
Directory exerciseDir, String version, ArgResults arguments) async {
_testCasesString = testCaseTemplate(exerciseName, specification);
print('Found: ${arguments['spec-path']}/exercises/$exerciseName/canonical-data.json');
Directory('${exerciseDir.path}/lib').createSync(recursive: true);
Directory('${exerciseDir.path}/test').createSync(recursive: true);
// Create files
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));
File('${exerciseDir.path}/analysis_options.yaml').writeAsStringSync(analysisOptionsTemplate());
File('${exerciseDir.path}/pubspec.yaml').writeAsStringSync(pubTemplate(exerciseName, version));
// Generate README
final dartRoot = '${dirname(Platform.script.toFilePath())}/..';
final configletLoc = '$dartRoot/bin/configlet';
final genSuccess = _runProcess(
configletLoc, ['generate', '$dartRoot', '--spec-path', '${arguments['spec-path']}', '--only', exerciseName]);
if (genSuccess) {
stdout.write('Successfully created README.md\n');
} else {
stderr.write('Warning: `configlet generate` exited with an error, \'README.md\' is likely malformed.\n');
}
// The output from file generation is not always well-formatted, use dartfmt to clean it up
final fmtSuccess = _runProcess('dart', ['run', 'dart_style:format', '-i', '0', '-l', '120', '-w', exerciseDir.path]);
if (fmtSuccess) {
stdout.write('Successfully created a rough-draft of tests at \'$testFileName\'.\n');
stdout.write('You should check this over and fix or refine as necessary.\n');
} else {
stderr
.write('Warning: dart_style:format exited with an error, files in \'${exerciseDir.path}\' may be malformed.\n');
}
// Install dependencies
Directory.current = exerciseDir;
final pubSuccess = _runProcess('dart', ['pub', 'get']);
assert(pubSuccess);
}
/// If a string contains a single backslash, we need to add another behind it, so the backslash remains.
String _escapeBackslash(String input) {
final result = <String>[];
input.split('').forEach((String value) {
if (value == r'\') {
result.add(value + value);
} else {
result.add(value);
}
});
return result.join();
}
String _escapeWhitespace(String input) => input..replaceAll('\\', '\\\\');
bool _containsWhitespaceCodes(String input) {
return input.contains('\n') || input.contains('\r') || input.contains('\t');
}
String _determineBestReturnType(List<dynamic> specCases) {
final expectedList = retrieveListOfExpected(specCases);
final dynamic first = expectedList.isNotEmpty ? expectedList.first : null;
if (first is Iterable) {
final iterableType = '${_getIterableType(first)}';
if (first is List) {
return 'List<$iterableType>';
}
if (first is Set) {
return 'Set<$iterableType>';
}
}
if (first is Map) {
return 'Map${_getMapType(first)}';
}
if (first is String) {
return 'String';
}
if (first is num) {
if (first is int) {
return 'int';
} else if (first is double) {
return 'double';
} else {
return 'num';
}
}
if (first is bool) {
return 'bool';
}
return '';
}
/// Parses through a list of test cases to assemble a list of all the expected values within the test cases.
Set<dynamic> retrieveListOfExpected(List<dynamic> testCases, {Set<dynamic> expectedTypeSet = _defaultSet}) {
for (var count = 0; count < testCases.length; count++) {
if (testCases[count] is Map) {
final entry = testCases[count] as Map;
bool addEntry = true;
if (entry.containsKey('expected')) {
if (entry['expected'] is Map) {
addEntry = !(entry['expected'] as Map).containsKey('error');
}
if (entry['expected'] is Iterable) {
addEntry = (entry['expected'] as Iterable).isNotEmpty;
}
if (addEntry) {
expectedTypeSet = Set<dynamic>.of(expectedTypeSet)..add(entry['expected']);
}
}
if (entry.containsKey('cases')) {
expectedTypeSet =
Set<dynamic>.of(retrieveListOfExpected(entry['cases'] as List, expectedTypeSet: expectedTypeSet));
}
}
if (testCases[count] is List) {
expectedTypeSet =
Set<dynamic>.of(retrieveListOfExpected(testCases[count] as List, expectedTypeSet: expectedTypeSet));
}
}
return expectedTypeSet;
}
/// Escapes single quotes found in a test case's description, in order to prevent errors.
String? _handleQuotes(String? input) {
if (input != null) {
final firstChar = input[0];
final lastChar = input[input.length - 1];
final shortenArgs = input.substring(1, input.length - 1).replaceAll('\'', '\\\'');
return '$firstChar$shortenArgs$lastChar';
} else {
return null;
}
}
/// `repr` takes in any object and tries to coerce it to a String in such a way that it is suitable to include in code.
/// Based on the python `repr` function, but only works for basic types: String, Iterable, Map, and primitive types
/// `typeDeclaration` is the determined return type and used to determine the type within collections.
String _repr(Object? x, {String? typeDeclaration}) {
if (x is String) {
String result = _escapeBackslash(x);
result = result
.replaceAll('\'', r"\'")
.replaceAll('\n', r'\n')
.replaceAll('\r', r'\r')
.replaceAll('\t', r'\t')
.replaceAll(r'$', r'\$');
return '\'$result\'';
}
if (x is Iterable) {
String iterableType;
if (typeDeclaration != null) {
final iterables = RegExp(r'List|Map|Set');
final knownType = '<${typeDeclaration.replaceFirst(iterables, '')}>';
final currentType = '<${_getIterableType(x)}>';
iterableType = knownType == currentType ? knownType : currentType;
} else {
iterableType = '<${_getIterableType(x)}>';
}
if (x is List) {
return '$iterableType[${x.map(_repr).join(', ')}]';
} else if (x is Set) {
return '$iterableType{${x.map(_repr).join(', ')}}';
}
}
if (x is Map) {
return _defineMap(x, '${_getMapType(x)}');
}
return '$x';
}
String _defineMap(Map x, String iterableType) {
final pairs = <String>[];
for (var k in x.keys) {
pairs.add('${_repr(k)}: ${_repr(x[k])}');
}
return '$iterableType{${pairs.join(', ')}}';
}
/// A helper method to get the inside type of an iterable
String _getIterableType(Iterable iter) {
final types = iter.map<String>(_getFriendlyType as String Function(dynamic)).toSet();
if (types.length == 1) {
return types.first;
}
return 'Object';
}
/// A helper method to get the inside type of a map
String _getMapType(Map map) {
final keyTypes = map.keys.map<String>(_getFriendlyType as String Function(dynamic)).toSet();
final valueTypes = map.values.map<String>(_getFriendlyType as String Function(dynamic)).toSet();
final mapKeyType = keyTypes.length == 1 ? keyTypes.first : 'dynamic';
final mapValueType = valueTypes.length == 1 ? valueTypes.first : 'dynamic';
return '<$mapKeyType, $mapValueType>';
}
/// Get a human-friendly type of a variable
String _getFriendlyType(Object x) {
if (x is String) {
return 'String';
}
if (x is Iterable) {
return 'List<${_getIterableType(x)}>';
}
if (x is Map) {
return 'Map<${_getIterableType(x.keys)}, ${_getIterableType(x.values)}>';
}
if (x is num) {
if (x is int) {
return 'int';
} else if (x is double) {
return 'double';
} else {
return 'num';
}
}
return x.runtimeType.toString();
}
// runProcess runs a process, writes any stdout/stderr output.
// Returns true if the cmd was successful, false otherwise
bool _runProcess(String cmd, List<String> arguments) {
final res = Process.runSync(cmd, arguments, runInShell: true);
if (!res.stdout.toString().isEmpty) {
stdout.write(res.stdout);
}
if (!res.stderr.toString().isEmpty) {
stderr.write(res.stderr);
}
return res.exitCode == 0;
}
void main(List<String> args) {
final arguments = _parser.parse(args);
final restArgs = arguments.rest;
if (restArgs.isEmpty) {
stderr.write(_parser.usage);
exit(1);
}
final exerciseName = restArgs.first;
final exerciseDir = Directory('exercises/${kebabCase(exerciseName)}');
// Create dir
final currentDir = Directory.current;
final exerciseFilename = snakeCase(exerciseName);
// Get test cases from canonical-data.json, format tests
if (arguments['spec-path'] != null) {
final canonicalFilePath = '${arguments['spec-path']}/exercises/$exerciseName/canonical-data.json';
try {
final canonicalDataJson = File(canonicalFilePath);
final source = canonicalDataJson.readAsStringSync();
final specification = json.decode(source) as Map<String, Object>;
final version = specification['version'].toString();
if (_doGenerate(exerciseDir, exerciseName, version)) {
_generateExercise(specification, exerciseFilename, exerciseName, exerciseDir, version, arguments);
}
} on FileSystemException {
stderr.write('Could not open file \'$canonicalFilePath\', exiting.\n');
exit(1);
} on FormatException {
stderr.write('File \'$canonicalFilePath\' is not valid JSON, exiting.\n');
exit(1);
}
} else {
print('Could not find: ${arguments['spec-path']}/exercises/$exerciseName/canonical-data.json');
}
Directory.current = currentDir;
}