package_map.dart 2.29 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:package_config/packages_file.dart' as packages_file;

7
import '../base/file_system.dart';
8
import '../base/platform.dart';
9

10
const String kPackagesFileName = '.packages';
11 12

Map<String, Uri> _parse(String packagesPath) {
13
  final List<int> source = fs.file(packagesPath).readAsBytesSync();
14
  return packages_file.parse(source,
15
      Uri.file(packagesPath, windows: platform.isWindows));
16 17 18 19 20
}

class PackageMap {
  PackageMap(this.packagesPath);

21 22
  static String get globalPackagesPath => _globalPackagesPath ?? kPackagesFileName;

23 24
  static String get globalGeneratedPackagesPath => fs.path.setExtension(globalPackagesPath, '.generated');

25 26 27 28
  static set globalPackagesPath(String value) {
    _globalPackagesPath = value;
  }

29 30
  static bool get isUsingCustomPackagesPath => _globalPackagesPath != null;

31 32
  static String _globalPackagesPath;

33 34
  final String packagesPath;

35 36
  /// Load and parses the .packages file.
  void load() {
Ian Hickson's avatar
Ian Hickson committed
37
    _map ??= _parse(packagesPath);
38 39 40 41
  }

  Map<String, Uri> get map {
    load();
42 43 44 45
    return _map;
  }
  Map<String, Uri> _map;

46
  /// Returns the path to [packageUri].
47 48 49 50
  String pathForPackage(Uri packageUri) => uriForPackage(packageUri).path;

  /// Returns the path to [packageUri] as Uri.
  Uri uriForPackage(Uri packageUri) {
51
    assert(packageUri.scheme == 'package');
52 53 54
    final List<String> pathSegments = packageUri.pathSegments.toList();
    final String packageName = pathSegments.removeAt(0);
    final Uri packageBase = map[packageName];
55
    if (packageBase == null) {
56
      return null;
57
    }
58
    final String packageRelativePath = fs.path.joinAll(pathSegments);
59
    return packageBase.resolveUri(fs.path.toUri(packageRelativePath));
60 61
  }

62
  String checkValid() {
63
    if (fs.isFileSync(packagesPath)) {
64
      return null;
65
    }
66
    String message = '$packagesPath does not exist.';
67
    final String pubspecPath = fs.path.absolute(fs.path.dirname(packagesPath), 'pubspec.yaml');
68
    if (fs.isFileSync(pubspecPath)) {
69
      message += '\nDid you run "flutter pub get" in this directory?';
70
    } else {
71
      message += '\nDid you run this command from the same directory as your pubspec.yaml file?';
72
    }
73 74 75
    return message;
  }
}