fix(dart/transform): Sanitize generated library names

Sanitize generated library names by removing unsafe characters and
ensuring that Dart keywords do not appear as library segments.
This commit is contained in:
Tim Blasi 2015-10-02 14:05:34 -07:00
parent 4ac29621f4
commit ba6e0e11fa
1 changed files with 10 additions and 8 deletions

View File

@ -1,5 +1,6 @@
library angular2.transform.common.code.source_module; library angular2.transform.common.code.source_module;
import 'package:analyzer/src/generated/scanner.dart' show Keyword;
import 'package:angular2/src/core/compiler/source_module.dart'; import 'package:angular2/src/core/compiler/source_module.dart';
import 'uri.dart'; import 'uri.dart';
@ -9,7 +10,8 @@ String writeSourceModule(SourceModule sourceModule, {String libraryName}) {
if (sourceModule == null) return null; if (sourceModule == null) return null;
var buf = new StringBuffer(); var buf = new StringBuffer();
var sourceWithImports = sourceModule.getSourceWithImports(); var sourceWithImports = sourceModule.getSourceWithImports();
var libraryName = _getLibName(sourceModule.moduleUrl); libraryName = _sanitizeLibName(
libraryName != null ? libraryName : sourceModule.moduleUrl);
buf..writeln('library $libraryName;')..writeln(); buf..writeln('library $libraryName;')..writeln();
sourceWithImports.imports.forEach((import) { sourceWithImports.imports.forEach((import) {
// Format for importLine := [uri, prefix] // Format for importLine := [uri, prefix]
@ -29,11 +31,11 @@ String writeSourceModule(SourceModule sourceModule, {String libraryName}) {
} }
final _unsafeCharsPattern = new RegExp(r'[^a-zA-Z0-9_\.]'); final _unsafeCharsPattern = new RegExp(r'[^a-zA-Z0-9_\.]');
String _getLibName(String moduleUrl) { String _sanitizeLibName(String moduleUrl) {
// TODO(tbosch): use `.replaceAll('/', '.')` here as well var sanitized =
// Also: replaceAll('asset:', ''). moduleUrl.replaceAll(_unsafeCharsPattern, '_').replaceAll('/', '.');
// Right now, this fails in some cases with Dart2Js, e.g. for (var keyword in Keyword.values) {
// (Error 'switch' is a reserved word and can't be used here. sanitized.replaceAll(keyword.syntax, '${keyword.syntax}_');
// library angular2_material.lib.src.components.switcher.switch.template.dart;) }
return moduleUrl.replaceAll(_unsafeCharsPattern, '_'); return sanitized;
} }