void (@NotNull Collection<? extends DataNode<LibraryData>> toImport, @Nullable ProjectData projectData, @NotNull Project project, @NotNull IdeModifiableModelsProvider modelsProvider) { if (projectData == null) return; // do not cleanup orphan project libraries if import runs from Project Structure Dialog // since libraries order entries cannot be imported for modules in that case // and hence orphans will be detected incorrectly if (modelsProvider instanceof ProjectStructureUIModifiableModelsProvider) return; final List<Library> orphanIdeLibraries = new SmartList<>(); final LibraryTable.ModifiableModel librariesModel = modelsProvider.getModifiableProjectLibrariesModel(); final Map<String, Library> namesToLibs = new HashMap<>(); final Set<Library> potentialOrphans = new HashSet<>(); RootPolicy<Void> excludeUsedLibraries = new RootPolicy<>() { @Override public Void visitLibraryOrderEntry(@NotNull LibraryOrderEntry ideDependency, Void value) { if (ideDependency.isModuleLevel()) { return null; } Library lib = ideDependency.getLibrary(); if (lib == null) { lib = namesToLibs.get(ideDependency.getLibraryName()); } if (lib != null) { potentialOrphans.remove(lib); } return null; } }; for (Library library: librariesModel.getLibraries()) { if (!ExternalSystemApiUtil.isExternalSystemLibrary(library, projectData.getOwner())) continue; namesToLibs.put(library.getName(), library); potentialOrphans.add(library); } for (Module module: modelsProvider.getModules()) { for (OrderEntry entry: modelsProvider.getOrderEntries(module)) { entry.accept(excludeUsedLibraries, null); } } for (Library lib: potentialOrphans) { if (!modelsProvider.isSubstituted(lib.getName())) { orphanIdeLibraries.add(lib); } } for (Library library: orphanIdeLibraries) { String libraryName = library.getName(); if (libraryName != null) { Library libraryToRemove = librariesModel.getLibraryByName(libraryName); if (libraryToRemove != null) { librariesModel.removeLibrary(libraryToRemove); } } } }