Skip to content
This repository has been archived by the owner on Feb 22, 2018. It is now read-only.

Commit

Permalink
fix(transformers): Fix relative URL lookup for transformers, and web
Browse files Browse the repository at this point in the history
Extracts logic used in the TypeRelativeUriGenerator to be used in other
transformers. This allows other transformers such as the ExpressionGenerator
and later the TemplateCacheGenerator to find relative resources.

Fixes asset resolution according to Barback rules which are defined here:
http://goo.gl/YDMRc2 specifically library assets are defined with packages
being in the URI and all other resources are considered web resources.

Closes #1649, #1651
  • Loading branch information
Ted Sander authored and rkirov committed Feb 2, 2015
1 parent f55b6bc commit 8d36167
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 29 deletions.
14 changes: 11 additions & 3 deletions lib/tools/transformer/referenced_uris.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'dart:async';

import 'package:analyzer/src/generated/ast.dart';
import 'package:analyzer/src/generated/element.dart';
import 'package:angular/tools/transformer/transformer_resource_url_resolver.dart';
import 'package:angular/tools/transformer/options.dart';
import 'package:barback/barback.dart';
import 'package:code_transformers/resolver.dart';
Expand All @@ -15,8 +16,10 @@ import 'package:path/path.dart' as path;
Future<Map<String, String>> gatherReferencedUris(Transform transform,
Resolver resolver, TransformOptions options,
{bool skipNonCached: false, bool templatesOnly: false}) {
var urlResolver =
new TransformerResourceUrlResolver(resolver, transform.primaryInput.id);
return new _Processor(transform, resolver, options, skipNonCached,
templatesOnly).process();
templatesOnly, urlResolver).process();
}

class _Processor {
Expand All @@ -26,6 +29,7 @@ class _Processor {
final Map<RegExp, String> templateUriRewrites = <RegExp, String>{};
final bool skipNonCached;
final bool templatesOnly;
final TransformerResourceUrlResolver urlResolver;

ConstructorElement cacheAnnotation;
ConstructorElement componentAnnotation;
Expand All @@ -35,7 +39,7 @@ class _Processor {
static const String componentAnnotationName = 'angular.core.annotation_src.Component';

_Processor(this.transform, this.resolver, this.options, this.skipNonCached,
this.templatesOnly) {
this.templatesOnly, this.urlResolver) {
for (var key in options.templateUriRewrites.keys) {
templateUriRewrites[new RegExp(key)] = options.templateUriRewrites[key];
}
Expand Down Expand Up @@ -199,6 +203,7 @@ class _Processor {

_CacheEntry uriToEntry(String uri, Element reference) {
uri = rewriteUri(uri);
uri = urlResolver.combineWithElement(reference, uri);
if (Uri.parse(uri).scheme != '') {
warn('Cannot cache non-local URIs. $uri', reference);
return null;
Expand All @@ -212,7 +217,10 @@ class _Processor {
warn('Cannot cache non-package absolute URIs. $uri', reference);
return null;
}
var assetId = new AssetId(transform.primaryInput.id.package, uri);
// Everything else is a resource in the web directory according to pub;
// as all packages URIs were handled above. As specified in this
// [Barback Doc](http://goo.gl/YDMRc2)
var assetId = new AssetId(transform.primaryInput.id.package, 'web/$uri');
return new _CacheEntry(uri, reference, assetId);
}

Expand Down
62 changes: 62 additions & 0 deletions lib/tools/transformer/transformer_resource_url_resolver.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
library angular.tools.transformer.angular_file_resolver;

import 'package:analyzer/src/generated/element.dart';
import 'package:code_transformers/resolver.dart';
import 'package:barback/barback.dart';

/// Resolver used to find absolute resources when in Transformers by combining
/// AST element locations and relative URIs.
class TransformerResourceUrlResolver {
final Resolver _resolver;
final AssetId _primaryAsset;

TransformerResourceUrlResolver(this._resolver, this._primaryAsset);

Uri findUriOfElement(Element type) {
var uri = _resolver.getImportUri(type.library, from: _primaryAsset);
var acceptable = (
(uri.isAbsolute && uri.scheme == 'package') ||
(uri.toString() == uri.path));
if (!acceptable) {
var errMsg = 'ERROR: Type "$type" has unsupported URI $uri';
throw errMsg;
}
if (uri.scheme != "package") {
// this is guaranteed to be a relative URL (e.g. type defined in a path
// imported file)
var path = _primaryAsset.path;
if (!path.startsWith('web/')) {
var errMsg = 'ERROR: Type "$type" is imported as a path not under web.';
throw errMsg;
}
uri = Uri.parse(path.substring('web/'.length)).resolve(uri.path);
}
return uri;
}

/// Given a AST [type] and [uri] if [uri] is relative combines it with the uri
/// of the element to make an absolute location relative to types uri.
/// Note: This logic should match [ResourceUrlResolver], but is separate as
/// transformers and Mirrors have different APIs to identify elements, and
/// calculate their URIs.
String combineWithElement(Element type, String uri) {
if (uri != null) {
if (uri.startsWith("/")) return uri;
if (uri.startsWith("packages/")) return "/" + uri;
}

var typeUri = findUriOfElement(type);

if (uri == null) {
uri = typeUri.path;
}
// If it's not absolute, then resolve it first
Uri resolved = typeUri.resolve(uri);

if (resolved.scheme == 'package') {
return '/packages/${resolved.path}';
} else {
return resolved.toString();
}
}
}
25 changes: 3 additions & 22 deletions lib/tools/transformer/type_relative_uri_generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'dart:async';
import 'package:analyzer/src/generated/ast.dart';
import 'package:analyzer/src/generated/element.dart';
import 'package:angular/tools/transformer/options.dart';
import 'package:angular/tools/transformer/transformer_resource_url_resolver.dart';
import 'package:barback/barback.dart';
import 'package:code_transformers/resolver.dart';
import 'package:path/path.dart' as path;
Expand Down Expand Up @@ -36,6 +37,7 @@ class TypeRelativeUriGenerator extends Transformer with ResolverTransformer {
transform.logger.warning('Unable to resolve $componentAnnotationName.');
}

var urlResolver = new TransformerResourceUrlResolver(resolver, id);
var annotatedTypes = resolver.libraries
.expand((lib) => lib.units)
.expand((unit) => unit.types)
Expand Down Expand Up @@ -69,28 +71,7 @@ class TypeRelativeUriGenerator extends Transformer with ResolverTransformer {
for (var type in annotatedTypes) {
outputBuffer.write(' ${importPrefixes[type.library]}${type.name}: ');

var uri = resolver.getImportUri(type.library,
from: transform.primaryInput.id);

var acceptable = (
(uri.isAbsolute && uri.scheme == "package") ||
(uri.toString() == uri.path));
if (!acceptable) {
var errMsg = 'ERROR: $runtimeType: Type "$type" has unsupported URI $uri';
transform.logger.error(errMsg);
throw errMsg;
}
if (uri.scheme != "package") {
// this is guaranteed to be a relative URL (e.g. type defined in a path
// imported file)
var path = transform.primaryInput.id.path;
if (!path.startsWith("web/")) {
var errMsg = 'ERROR: $runtimeType: Type "$type" is imported as a path not under web.';
transform.logger.error(errMsg);
throw errMsg;
}
uri = Uri.parse(path.substring("web/".length)).resolve(uri.path);
}
var uri = urlResolver.findUriOfElement(type);
outputBuffer.write("Uri.parse(r'''$uri'''),\n");
}
_writeFooter(outputBuffer);
Expand Down
35 changes: 31 additions & 4 deletions test/tools/transformer/expression_generator_spec.dart
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ main() {
import 'package:angular/angular.dart';
@Component(
templateUrl: 'lib/foo.html',
templateUrl: 'foo.html',
selector: 'my-component')
class FooComponent {}
Expand All @@ -79,7 +79,7 @@ main() {
main() {}
''',
'a|lib/foo.html': '''
'a|web/foo.html': '''
<div>{{template.contents}}</div>''',
'b|lib/bar.html': '''
<div>{{bar}}</div>''',
Expand Down Expand Up @@ -119,14 +119,41 @@ main() {
symbols: []);
});

it('should respect relative URLs', () {
return generates(phases,
inputs: {
'a|web/main.dart': '''
import 'package:b/bar.dart';
main() {}
''',
'b|lib/bar.dart': '''
import 'package:angular/angular.dart';
@Component(
templateUrl: 'bar.html',
selector: 'my-component')
class BarComponent {}
''',
'b|lib/bar.html': '''
<div>{{bar}}</div>''',
'a|web/index.html': '''
<script src='main.dart' type='application/dart'></script>''',
'angular|lib/angular.dart': libAngular,
},
getters: ['bar'],
setters: ['bar'],
symbols: []);
});

it('should generate expressions for variables found in superclass', () {
return generates(phases,
inputs: {
'a|web/main.dart': '''
import 'package:angular/angular.dart';
@Component(
templateUrl: 'lib/foo.html',
templateUrl: 'foo.html',
selector: 'my-component')
class FooComponent extends BarComponent {
@NgAttr('foo')
Expand All @@ -140,7 +167,7 @@ main() {
main() {}
''',
'a|lib/foo.html': '''
'a|web/foo.html': '''
<div>{{template.foo}}</div>
<div>{{template.bar}}</div>''',
'a|web/index.html': '''
Expand Down

0 comments on commit 8d36167

Please sign in to comment.