getImportDirectives method

Future<List<String>> getImportDirectives({
  1. Uri? uri,
  2. String? source,
  3. bool alsoImportOriginalFile = false,
})

Implementation

Future<List<String>> getImportDirectives({
  Uri? uri,
  String? source,
  bool alsoImportOriginalFile = false,
}) async {
  if (uri != null && source != null) {
    throw ArgumentError(
        "either uri or source must be non-null, but not both");
  }

  if (uri == null && source == null) {
    throw ArgumentError(
        "either uri or source must be non-null, but not both");
  }

  if (alsoImportOriginalFile == true && uri == null) {
    throw ArgumentError(
        "flag 'alsoImportOriginalFile' may only be set if 'uri' is also set");
  }
  Package? package = await getPackageFromUri(uri);
  String? trailingSegments = uri?.pathSegments.sublist(1).join('/');
  final fileUri =
      package?.packageUriRoot.resolve(trailingSegments ?? '') ?? uri;
  final text = source ?? File.fromUri(fileUri!).readAsStringSync();
  final importRegex = RegExp("import [\\'\\\"]([^\\'\\\"]*)[\\'\\\"];");

  final imports = importRegex.allMatches(text).map((m) {
    final importedUri = Uri.parse(m.group(1)!);

    if (!importedUri.isAbsolute) {
      final path = fileUri
          ?.resolve(importedUri.path)
          .toFilePath(windows: Platform.isWindows);
      return "import 'file:${absolute(path!)}';";
    }

    return text.substring(m.start, m.end);
  }).toList();

  if (alsoImportOriginalFile) {
    imports.add("import '$uri';");
  }

  return imports;
}