OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2015, 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 /// Utility methods used by more than one library in the package. |
| 6 library package_config.util; |
| 7 |
| 8 import "package:charcode/ascii.dart"; |
| 9 |
| 10 /// Tests whether something is a valid Dart identifier/package name. |
| 11 bool isIdentifier(String string) { |
| 12 if (string.isEmpty) return false; |
| 13 int firstChar = string.codeUnitAt(0); |
| 14 int firstCharLower = firstChar |= 0x20; |
| 15 if (firstCharLower < $a || firstCharLower > $z) { |
| 16 if (firstChar != $_ && firstChar != $$) return false; |
| 17 } |
| 18 for (int i = 1; i < string.length; i++) { |
| 19 int char = string.codeUnitAt(i); |
| 20 int charLower = char | 0x20; |
| 21 if (charLower < $a || charLower > $z) { // Letters. |
| 22 if ((char ^ 0x30) <= 9) continue; // Digits. |
| 23 if (char == $_ || char == $$) continue; // $ and _ |
| 24 if (firstChar != $_ && firstChar != $$) return false; |
| 25 } |
| 26 } |
| 27 return true; |
| 28 } |
| 29 |
| 30 |
| 31 /// Validate that a Uri is a valid package:URI. |
| 32 String checkValidPackageUri(Uri packageUri) { |
| 33 if (packageUri.scheme != "package") { |
| 34 throw new ArgumentError.value(packageUri, "packageUri", |
| 35 "Not a package: URI"); |
| 36 } |
| 37 if (packageUri.hasAuthority) { |
| 38 throw new ArgumentError.value(packageUri, "packageUri", |
| 39 "Package URIs must not have a host part"); |
| 40 } |
| 41 if (packageUri.hasQuery) { |
| 42 // A query makes no sense if resolved to a file: URI. |
| 43 throw new ArgumentError.value(packageUri, "packageUri", |
| 44 "Package URIs must not have a query part"); |
| 45 } |
| 46 if (packageUri.hasFragment) { |
| 47 // We could leave the fragment after the URL when resolving, |
| 48 // but it would be odd if "package:foo/foo.dart#1" and |
| 49 // "package:foo/foo.dart#2" were considered different libraries. |
| 50 // Keep the syntax open in case we ever get multiple libraries in one file. |
| 51 throw new ArgumentError.value(packageUri, "packageUri", |
| 52 "Package URIs must not have a fragment part"); |
| 53 } |
| 54 if (packageUri.path.startsWith('/')) { |
| 55 throw new ArgumentError.value(packageUri, "packageUri", |
| 56 "Package URIs must not start with a '/'"); |
| 57 } |
| 58 int firstSlash = packageUri.path.indexOf('/'); |
| 59 if (firstSlash == -1) { |
| 60 throw new ArgumentError.value(packageUri, "packageUri", |
| 61 "Package URIs must start with the package name followed by a '/'"); |
| 62 } |
| 63 String packageName = packageUri.path.substring(0, firstSlash); |
| 64 if (!isIdentifier(packageName)) { |
| 65 throw new ArgumentError.value(packageUri, "packageUri", |
| 66 "Package names must be valid identifiers"); |
| 67 } |
| 68 return packageName; |
| 69 } |
OLD | NEW |