packageImportForFile function

String? packageImportForFile({
  1. required String absoluteFilePath,
  2. required String packageRoot,
  3. required String packageName,
})

Convert an absolute Dart file under lib/ to a package: import URI.

Implementation

String? packageImportForFile({
  required String absoluteFilePath,
  required String packageRoot,
  required String packageName,
}) {
  final libDir = path.normalize(path.join(packageRoot, 'lib'));
  final file = path.normalize(absoluteFilePath);
  final prefix = libDir.endsWith(path.separator) ? libDir : '$libDir${path.separator}';
  if (!file.startsWith(prefix)) return null;
  final rel = path.relative(file, from: libDir).replaceAll(r'\', '/');
  return 'package:$packageName/$rel';
}