Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an option to Allocator to resolve relative imports #148

Closed
matanlurey opened this issue Oct 17, 2017 · 1 comment
Closed

Add an option to Allocator to resolve relative imports #148

matanlurey opened this issue Oct 17, 2017 · 1 comment
Assignees
Milestone

Comments

@matanlurey
Copy link
Contributor

As of right now, invalid code is produced when referring to files outside of lib/:

test/
  foo_test.dart
  foo_test.g.dart // <-- Generated

In foo_test.g.dart, an import is added like:

import 'asset:foo/test/foo_test.dart';

It should instead be:

import 'foo_test.dart';

I've solved this elsewhere using a relativeTo parameter:

  /// Returns a [Uri] for this path that can be used in a Dart import statement.
  Uri toDartUri({Uri relativeTo}) {
    if (relativeTo != null) {
      // Attempt to construct relative import.
      Uri normalizedBase = relativeTo.normalizePath();
      List<String> baseSegments = pkg_path.split(normalizedBase.path)
        ..removeLast();
      List<String> targetSegments = pkg_path.split(toAbsoluteUri().path);
      if (baseSegments.first == targetSegments.first &&
          baseSegments[1] == targetSegments[1]) {
        // Ok, we're in the same package and in the same top-level directory.
        String relativePath = pkg_path.relative(
            targetSegments.skip(2).join('/'),
            from: baseSegments.skip(2).join('/'));
        return new Uri(path: relativePath);
      }
    }

    var pathSegments = pkg_path.split(path);

    if (pathSegments.first != 'lib') {
      throw new StateError(
          'Cannot construct absolute import URI from ${relativeTo} '
          'to a non-lib Dart file: ${toAbsoluteUri()}');
    }

    var packagePath = pkg_path.joinAll(pathSegments.sublist(1));
    return new Uri(
        scheme: isDartSdk ? _dartPackage : 'package',
        path: isDartSdk ? path : '$package/$packagePath');
  }
@matanlurey matanlurey added this to the 2.0 milestone Oct 17, 2017
@matanlurey matanlurey self-assigned this Oct 17, 2017
@matanlurey
Copy link
Contributor Author

Not necessary to solve in code_builder for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant