parseFromStacktrace static method

Future<Library> parseFromStacktrace()

Decode the StackTrace to try and extract information about the current library.

This should only be used within the "main" of a test file.

Implementation

static Future<Library> parseFromStacktrace() async {
  const testFilePath = '___temporary_test____.dart';

  final pubSpec = await PubSpec.load(Directory.current);

  // Relying on the Stacktrace to obtain the current test file name
  final stacktrace = Trace.from(StackTrace.current);
  final mainFrame = stacktrace.frames
      .lastWhereOrNull((element) => element.uri.isScheme('FILE'));

  if (mainFrame == null || pubSpec.name == null) {
    throw StateError('Failed to determine the current test file location');
  }

  final tempTestFilePath = _path.join(
    Directory.fromUri(Uri.file(mainFrame.library)).parent.path,
    testFilePath,
  );

  return Library(
    packageName: pubSpec.name!,
    path: _path.normalize(tempTestFilePath).replaceAll(r'\', '/'),
    // packageConfig: null, // use package definition from the current Isolate
  );
}