package_map.dart 2.33 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// 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 '../globals.dart' as globals;
8

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

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

class PackageMap {
  PackageMap(this.packagesPath);

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

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

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

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

30 31
  static String _globalPackagesPath;

32 33
  final String packagesPath;

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

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

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

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

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