OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 library name_validator; |
| 6 |
| 7 import 'dart:io'; |
| 8 |
| 9 import '../entrypoint.dart'; |
| 10 import '../io.dart'; |
| 11 import '../validator.dart'; |
| 12 |
| 13 /// Dart reserved words, from the Dart spec. |
| 14 final _RESERVED_WORDS = [ |
| 15 "abstract", "as", "dynamic", "export", "external", "factory", "get", |
| 16 "implements", "import", "library", "operator", "part", "set", "static", |
| 17 "typedef" |
| 18 ]; |
| 19 |
| 20 /// A validator that validates the name of the package and its libraries. |
| 21 class NameValidator extends Validator { |
| 22 NameValidator(Entrypoint entrypoint) |
| 23 : super(entrypoint); |
| 24 |
| 25 Future validate() { |
| 26 _checkName(entrypoint.root.name, 'Package name "${entrypoint.root.name}"'); |
| 27 |
| 28 var libDir = join(entrypoint.root.dir, "lib"); |
| 29 return dirExists(libDir).chain((libDirExists) { |
| 30 if (!libDirExists) return new Future.immediate([]); |
| 31 return listDir(libDir, recursive: true); |
| 32 }).transform((files) { |
| 33 for (var file in files) { |
| 34 if (file.contains("/src/")) continue; |
| 35 if (new Path(file).extension != 'dart') continue; |
| 36 var libName = new Path(file).filenameWithoutExtension; |
| 37 _checkName(libName, 'The name of "$file", "$libName",'); |
| 38 } |
| 39 }); |
| 40 } |
| 41 |
| 42 void _checkName(String name, String description) { |
| 43 if (name == "") { |
| 44 errors.add("$description may not be empty."); |
| 45 } else if (!new RegExp(r"^[a-zA-Z0-9_]*$").hasMatch(name)) { |
| 46 errors.add("$description must be a valid Dart identifier: it may only " |
| 47 "contain letters, numbers, and underscores."); |
| 48 } else if (!new RegExp(r"^[a-zA-Z]").hasMatch(name)) { |
| 49 errors.add("$description must be a valid Dart identifier: it must begin " |
| 50 "with a letter."); |
| 51 } else if (_RESERVED_WORDS.contains(name.toLowerCase())) { |
| 52 errors.add("$description must be a valid Dart identifier: it may not be " |
| 53 "a reserved word in Dart."); |
| 54 } else if (new RegExp(r"[A-Z]").hasMatch(name)) { |
| 55 warnings.add('$description should be lower-case. Maybe use ' |
| 56 '"${_unCamelCase(name)}"?'); |
| 57 } |
| 58 } |
| 59 |
| 60 String _unCamelCase(String source) { |
| 61 var builder = new StringBuffer(); |
| 62 var lastMatchEnd = 0; |
| 63 for (var match in new RegExp(r"[a-z]([A-Z])").allMatches(source)) { |
| 64 builder |
| 65 ..add(source.substring(lastMatchEnd, match.start + 1)) |
| 66 ..add("_") |
| 67 ..add(match.group(1).toLowerCase()); |
| 68 lastMatchEnd = match.end; |
| 69 } |
| 70 builder.add(source.substring(lastMatchEnd)); |
| 71 return builder.toString().toLowerCase(); |
| 72 } |
| 73 } |
OLD | NEW |