removeDuplicateLibraries method

List<String> removeDuplicateLibraries(
  1. List<String> classpath
)

Removes duplicate libraries from the classpath, keeping only the newest version.

When multiple versions of the same JAR file are found in the classpath, this function keeps the newest version and removes older versions.

classpath The list of classpath entries to optimize

Returns an optimized classpath list with duplicates removed

Implementation

List<String> removeDuplicateLibraries(List<String> classpath) {
  RegExp versionPattern = RegExp(r'-([\d.]+(?:-[\w.]+)?)\.jar$');
  final Map<String, String> libraryPaths = {};
  final Map<String, String> libraryVersions = {};

  for (final path in classpath) {
    final fileName = p.basename(path);
    final match = versionPattern.firstMatch(fileName);

    if (match != null) {
      final version = match.group(1)!;
      final baseName = fileName.substring(0, fileName.indexOf("-$version.jar"));

      if (libraryVersions.containsKey(baseName)) {
        final existingVersion = libraryVersions[baseName]!;

        if (_compareVersions(version, existingVersion) > 0) {
          debugPrint('Replacing $baseName $existingVersion with $version');
          libraryVersions[baseName] = version;
          libraryPaths[baseName] = path;
        }
      } else {
        libraryVersions[baseName] = version;
        libraryPaths[baseName] = path;
      }
    } else {
      libraryPaths[fileName] = path;
    }
  }

  final optimizedClasspath = libraryPaths.values.toList();

  if (classpath.length != optimizedClasspath.length) {
    debugPrint('Optimized classpath: removed ${classpath.length - optimizedClasspath.length} duplicate libraries');
  }

  return optimizedClasspath;
}