package_map.dart 2.16 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 23 24 25 26
  static String get globalPackagesPath => _globalPackagesPath ?? kPackagesFileName;

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

27 28
  static bool get isUsingCustomPackagesPath => _globalPackagesPath != null;

29 30
  static String _globalPackagesPath;

31 32
  final String packagesPath;

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

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

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

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

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