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."); | |
Bob Nystrom
2012/12/06 02:26:43
We should discuss this, but I'm leaning towards th
| |
45 } else if (!new RegExp(r"^[a-zA-Z0-9_]*$").hasMatch(name)) { | |
46 errors.add("$description may only contain letters, numbers, and " | |
47 "underscores."); | |
48 } else if (!new RegExp(r"^[a-zA-Z]").hasMatch(name)) { | |
49 errors.add("$description must begin with a letter."); | |
Bob Nystrom
2012/12/06 02:26:43
Or an underscore?
| |
50 } else if (new RegExp(r"[A-Z]").hasMatch(name)) { | |
51 errors.add('$description must be lower-case. Maybe use ' | |
52 '"${_unCamelCase(name)}"?'); | |
53 } else if (_RESERVED_WORDS.contains(name)) { | |
54 errors.add("$description may not be a reserved word in Dart."); | |
55 } | |
56 } | |
57 | |
58 String _unCamelCase(String source) { | |
59 var builder = new StringBuffer(); | |
60 var lastMatchEnd = 0; | |
61 for (var match in new RegExp(r"[a-z]([A-Z])").allMatches(source)) { | |
62 builder | |
63 ..add(source.substring(lastMatchEnd, match.start + 1)) | |
64 ..add("_") | |
65 ..add(match.group(1).toLowerCase()); | |
66 lastMatchEnd = match.end; | |
67 } | |
68 builder.add(source.substring(lastMatchEnd)); | |
69 return builder.toString().toLowerCase(); | |
70 } | |
71 } | |
OLD | NEW |