From 9c8914715e2dff19b1dedf7d2da9b450bee978f6 Mon Sep 17 00:00:00 2001 From: Matt Pennig Date: Thu, 20 Jul 2023 14:38:53 -0500 Subject: [PATCH] Allow passing multiple index stores to unused imports tool (#50) Useful for operating on per-module index stores. To wit, an unused `import B` in module A will only be marked as unused if the tool can collect the units from A and the USRs from B. --- Sources/unused-imports/main.swift | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/Sources/unused-imports/main.swift b/Sources/unused-imports/main.swift index 5809939..e302ee3 100644 --- a/Sources/unused-imports/main.swift +++ b/Sources/unused-imports/main.swift @@ -8,6 +8,18 @@ private let ignoreRegex = try Regex(#"// *@ignore-import$"#) private var cachedLines = [String: [String.SubSequence]]() private struct Configuration: Decodable { + static func attemptingPath(_ path: String?) -> Configuration? { + guard let path else { return nil } + do { + return try JSONDecoder().decode( + Configuration.self, + from: try Data(contentsOf: URL(fileURLWithPath: path)) + ) + } catch { + return nil + } + } + let ignoredFileRegex: Regex? let ignoredModuleRegex: Regex? let alwaysKeepImports: Set @@ -144,7 +156,7 @@ private func collectUnitsAndRecords(indexStorePath: String) -> [(UnitReader, Rec } private func main( - indexStorePath: String, + indexStorePaths: [String], configuration: Configuration) { if let directory = ProcessInfo.processInfo.environment["BUILD_WORKSPACE_DIRECTORY"] { @@ -153,7 +165,7 @@ private func main( let pwd = FileManager.default.currentDirectoryPath var filesToDefinitions: [String: References] = [:] - let unitsAndRecords = collectUnitsAndRecords(indexStorePath: indexStorePath) + let unitsAndRecords = indexStorePaths.flatMap(collectUnitsAndRecords(indexStorePath:)) var modulesToUnits: [String: [UnitReader]] = [:] var allModuleNames = Set() @@ -230,17 +242,15 @@ private func main( } } -if CommandLine.arguments.count == 3 { - let configurationData = try! Data(contentsOf: URL(fileURLWithPath: CommandLine.arguments[1])) - let configuration = try! JSONDecoder().decode(Configuration.self, from: configurationData) - +let arguments = CommandLine.arguments.dropFirst() +if let configuration = Configuration.attemptingPath(arguments.first) { main( - indexStorePath: CommandLine.arguments[2], + indexStorePaths: Array(arguments.dropFirst()), configuration: configuration ) } else { main( - indexStorePath: CommandLine.arguments[1], + indexStorePaths: Array(arguments), configuration: Configuration() ) }