package_map.dart 2.1 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 8
import '../base/file_system.dart';

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

Map<String, Uri> _parse(String packagesPath) {
12
  final List<int> source = fs.file(packagesPath).readAsBytesSync();
13 14 15 16 17 18
  return packages_file.parse(source, new Uri.file(packagesPath));
}

class PackageMap {
  PackageMap(this.packagesPath);

19 20 21 22 23 24
  static String get globalPackagesPath => _globalPackagesPath ?? kPackagesFileName;

  static set globalPackagesPath(String value) {
    _globalPackagesPath = value;
  }

25 26
  static bool get isUsingCustomPackagesPath => _globalPackagesPath != null;

27 28
  static String _globalPackagesPath;

29 30
  final String packagesPath;

31 32
  /// Load and parses the .packages file.
  void load() {
Ian Hickson's avatar
Ian Hickson committed
33
    _map ??= _parse(packagesPath);
34 35 36 37
  }

  Map<String, Uri> get map {
    load();
38 39 40 41
    return _map;
  }
  Map<String, Uri> _map;

42
  /// Returns the path to [packageUri].
43 44 45 46
  String pathForPackage(Uri packageUri) => uriForPackage(packageUri).path;

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

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