getRepositoryUrl function

Future<String?> getRepositoryUrl(
  1. String packageName
)

Fetches the GitHub repository URL of a package from pub.dev.

Returns null if the package does not exist or the repository URL is not available.

Implementation

Future<String?> getRepositoryUrl(String packageName) async {
  final url = 'https://pub.dev/api/packages/$packageName';
  final response = await http.get(Uri.parse(url));

  if (response.statusCode == 200) {
    final data = json.decode(response.body);

    // coverage:ignore-start
    final repositoryUrl = data['latest']['pubspec']['repository'] as String?;
    if (repositoryUrl != null) {
      return repositoryUrl;
    }

    // If the repository URL is not available, try to get the homepage URL.
    final homepage = data['latest']['pubspec']['homepage'] as String?;
    if (homepage != null && homepage.contains('github.com')) {
      return homepage;
    }
    // coverage:ignore-end

    return null;
  } else {
    // Package not found or an error occurred.
    return null;
  }
}