Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unused import rule transitive dependencies #5622

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 26 additions & 8 deletions Source/SwiftLintBuiltInRules/Rules/Lint/UnusedImportRule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -118,17 +118,11 @@ private extension SwiftLintFile {
)
}

let unusedImportUsages = rangedAndSortedUnusedImports(of: Array(unusedImports))
.map { ImportUsage.unused(module: $0, range: $1) }

guard configuration.requireExplicitImports else {
return unusedImportUsages
}

/// Find the missing imports, which should be imported, but are not.
let currentModule = (compilerArguments.firstIndex(of: "-module-name")?.advanced(by: 1))
.map { compilerArguments[$0] }

let missingImports = usrFragments
var missingImports = usrFragments
.subtracting(imports + [currentModule].compactMap({ $0 }))
.filter { module in
let modulesAllowedToImportCurrentModule = configuration.allowedTransitiveImports
Expand All @@ -140,6 +134,30 @@ private extension SwiftLintFile {
imports.isDisjoint(with: modulesAllowedToImportCurrentModule)
}

// Check if unused imports were used for transitive imports
var foundUmbrellaModules = Set<String>()
for missingImport in missingImports {
let umbrellaModules = configuration.allowedTransitiveImports
.filter { $0.transitivelyImportedModules.contains(missingImport) }
.map { $0.importedModule }

umbrellaModules.forEach { umbrellaModule in
missingImports.remove(missingImport)
if unusedImports.contains(umbrellaModule) {
foundUmbrellaModules.insert(umbrellaModule)
}
}
}

unusedImports.subtract(foundUmbrellaModules)

let unusedImportUsages = rangedAndSortedUnusedImports(of: Array(unusedImports))
.map { ImportUsage.unused(module: $0, range: $1) }

guard configuration.requireExplicitImports else {
return unusedImportUsages
}

return unusedImportUsages + missingImports.sorted().map { .missing(module: $0) }
}

Expand Down
Loading